Kmp是为了解决原字符串是否包含子字符串的问题,在这里记录一下Java的实现代码,并且分享一下学习Kmp的网址
https://blog.sengxian.com/algorithms/kmp
public int[] getNextArray(String sonStr){
char[]son = sonStr.toCharArray();
int[]next = new int[son.length];
next[0] = -1;
for(int i =1 ;i< son.length;i++){
j = next[i-1];
while(j!=-1 && son[j]!=son[i-1]) j=next[j];
next[i]=j+1;
}
return next;
}
public int KmpMatch(String originStr,String sonStr){
char[]son = sonStr.toCharArray();
char[]origin = originStr.toCharArray();
int[]next = getNextArray(sonStr);
int i = 0;
int j = 0;
while(i<origin.length && j<son.length){
if(j==-1 || son[j] == origin[i]){
i++;
j++;
}else j = next[j];
}
if( j == son.length) return i-j;
else return -1;
}