=nepublic class KMP {
public static void main(String[] args) {
String str2 = "abcdassabe"; //{-1,0,0,0,0,1,0,0,1,2}
int []next =new int[str2.length()];
new KMP().getNext(str2.toCharArray(),next);
for (int i : next) {
System.out.println(i);
}
}
private void getNext(char[] str2, int[] next) {
int j = -1; //前缀
int i = 0; //后缀
next[0]=-1; //默认初始化3个参数,next[0]=-1 方便回滚 next[1]=0
while (i<=str2.length-2){ //退出条件很重要,j给赋值给了后一位的next[i]
if(j==-1||str2[j]==str2[i]){//2个条件触发前进
i++;
j++;
next[i]=j;//赋值 关系next[i]=j j=next[j]
}else {
j=next[j];//只回滚j
}
}
}
}