No hay mucho que decir directamente sobre el código. Tengo tiempo para escribir pensamientos y principios, que es definitivamente el más fácil de entender.
public class KmpArithmetic {
public static int kmp(String str,String tar){
//获得next数组
int[] next=getNext(tar);
for (int i = 0,j=0; i < str.length(); i++) {
//如果已经部分匹配且后面部分不匹配
while(j>0&&str.charAt(i)!=tar.charAt(j)){
//则根据next数组回溯至前后缀相同且最长的位置。
j=next[j-1];
}
//如果相同则移动模型的下标。
if(str.charAt(i)==tar.charAt(j)){
j++;
}
//如果模型下标到达最后说明匹配成功,返回首字母下标。
if(j==tar.length()){
return i-j+1;
}
}//for
return -1;
}
public static int[] getNext(String tar){
int[] next=new int[tar.length()];
int k=0;
//next数组表示前缀和后缀相同时,其相同的长度。
next[0]=0;
//模型和模型自己匹配,找到其相同前后缀的长度。
for (int i = 1; i < next.length; i++) {
while(k>0&&tar.charAt(k)!=tar.charAt(i)){
k=next[k-1];
}
if(tar.charAt(k)==tar.charAt(i)){
k++;
}
next[i]=k;
}
return next;
}
public static void main(String[] args) {
String str="aaabaa";
String obj="aaba";
int[] next=getNext(obj);
System.out.println(kmp(str, obj));
}
}