Implement strStr()
Given two strings, haystack and needle, you need to determine if needle is the substring of haystack.
Solution:
You can simply use the O(n^2) method to compare the two strings. And I'd like to talk about KMP algorithm.
1. Denote that next[i] is the length of the longest common prefix and suffix of length i. Also we can see that next[i] stands for the index of the character right after the commom prefix and suffix. For current i, j is the index of next character we would compare with i.
2. We find the next array of needle first. The picture shows the needle string and the shadow parts are the same. now we compare i and j.
we see that j is next[i] (index starts from 0 and length starts from 1)
if s[j]==s[i] we simply let j plus one and next[i+1] = j. Remember that next[i] is the length of common prefix and suffix of length i.
if s[j]!=s[i] we seek for some patterns in the shadow part. In the picture, we have the double shadowed area the same. Now we can consider new j and i. New j is actually next[j]. Therefore we can continue this step until we find s[j]==s[i] or j == 0.
if s[j]==s[i], we let j plus one. Then we can set next[i+1] to j.
3. Here we get the next array of needle string. And we can use this array to match the needle and haystack. The picture shows the matching and we have a match start which means that from that point the two string matches. and if haystack[i] == needle[j], we just need to add one to j and go on matching. Otherwise we need to skip to next[j] as the second picture shows. we continue this step until needle[j]==haystack[i] or j == 0. If needle[j] == haystack[i], we let j plus one. If j is equal to the length of the needle, which means the two strings are matched, we can return i-j+1; After the loop, we just return -1 as no matching.
Code:
public class Solution { public int strStr(String haystack, String needle) { if(needle.length()<1){ return 0; } if(needle.length()>haystack.length()){ return -1; } if(needle.length()==haystack.length()){ if(needle.equals(haystack)){ return 0; }else { return -1; } } int length = haystack.length(); int[] next = getNext(needle); int j = 0; for(int i = 0; i < length; i++){ while(j>0&&haystack.charAt(i)!=needle.charAt(j)){ j=next[j]; } if(haystack.charAt(i)==needle.charAt(j)){ j++; } if(j==needle.length()){ return i-j+1; } } return -1; } public int[] getNext(String s){ int length = s.length(); int[] next = new int[length+1]; int j = 0; next[1]=0; for(int i = 1; i < length; i++){ while(j>0&&s.charAt(i)!=s.charAt(j)){ j=next[j]; } if(s.charAt(i)==s.charAt(j)){ j++; } next[i+1]=j; } return next; } }

浙公网安备 33010602011771号