题目
nex[i]:[0,i-1]前缀与后缀重合的最长前缀长度。
class Solution {
public int[] getNex(String s){
int[] nex=new int[s.length()+1];
int i=0,k=-1;nex[0]=-1;
while(i<s.length()){
if(k==-1||s.charAt(i)==s.charAt(k)) nex[++i]=++k;
else k=nex[k];
}
return nex;
}
public int strStr(String haystack, String needle) {
int n=haystack.length(),m=needle.length();
int[] nex=getNex(needle);
int i=0,j=0;
while(i<n&&j<m){
if(j==-1||haystack.charAt(i)==needle.charAt(j)) {++i;++j;}
else j=nex[j];
}
if(j==m) return i-m;
return -1;
}
}