//kmp算法
//算法思路,先整理待匹配的字符串s,next[index]=j,意思是,从j-1往前走的字符串s1==从index往前走同样长度的字符串s2
// 整理next[]的时间复杂度为O(n),s[index+1]的匹配长度要么等于s[index]+1,要么等于s[index]-k1*m1-k2*m2...
// 证明思路便是考虑s[index+1]的匹配长度基于s[index]及对其的操作,然后累加可至s[s.length-1]的匹配长度l,而且 l>=0&&l<s.length
//然后匹配字符串s与S,当s[i]!=S[k]时,令i=next[i-1],继续匹配
借助了别人的思路,非常简洁:
public String strStr(String haystack, String needle) {
if(needle.equals("")) return haystack;
int[] next=getNext(needle);
for(int i=0,k=0;i<haystack.length();i++){
while(k>0&&haystack.charAt(i)!=needle.charAt(k))//简洁
k=next[k-1];
if(haystack.charAt(i)==needle.charAt(k))
k++;
if(k==needle.length())
return haystack.substring(i-needle.length()+1);
}
return null;
}
//next[0]=0,
//next[i]==j,意味着needle[j-1]==needle[i],needle[j]是下一个要比较的
public int[] getNext(String needle){
int[] next=new int[needle.length()];
for(int i=1,k=0;i<needle.length();i++){
while(k>0&&needle.charAt(k)!=needle.charAt(i))
k=next[k-1]; //就这比较绕
if(needle.charAt(k)==needle.charAt(i))//如果==next[0]则为1否则还是0
k++;
next[i]=k;
}
return next;
}