Topic:
Implement strStr ().
Returns A pointer to the first occurrence of needle in haystack, or null if needle are not part of haystack.
Parse: Implements the Strstr () method, given the string haystack and needle, to return the position of the first occurrence of needle in haystack. The general solution to the problem is very simple, and the substring starting with each character in Haystack is compared to the needle, and if equal returns the substring at the beginning of the character. The time complexity of the algorithm is O (m*n), M is the length of haystack, and N is the length of needle.
I use the KMP algorithm to implement the string alignment problem, first for the pattern string needle to find its next array, and then traverse the haystack string.
The Java AC code is as follows:
public class Solution {public String strStr (String haystack, string needle) {if (haystack = null | | needle = NULL)
{return null;
} int[] Next = getNext (needle);
int PS = 0, PH = pS, PN = 0;
while (PS + needle.length () <= haystack.length ()) {if (PN = = Needle.length ()) {return haystack.substring (PS);
} else if (Haystack.charat (PS + pH) = = Needle.charat (PN)) {ph++;
pn++;
} else if (NEXT[PN + 1] = = 0) {PH = PN = 0;
ps++;
} else {PH-= (PN-NEXT[PN]);
PS + = (PN-NEXT[PN]);
PN = NEXT[PN];
}} return null;
} public static int[] GetNext (String needle) {int[] next = new Int[needle.length () + 1];
Next[0] =-1;
Needle = ' $ ' + needle; for (int i = 1; i < needle.length (); i++) {if (next[i-1] = = 0) {Next[i] = Needle.charat (i) = = Needle.charat ( 1)?
1:0;
} else {int before = next[i-1]; while (Before! =-1) {if (Needle.charat (before + 1) = = Needle.charat (i)) {Next[i]= before + 1;
Break
} else {before = Next[before];
}}}} return to Next; }
}