KMP算法
作者:binnext求解的代码,目的是找到当前i位置,如果下一个不匹配,需要回溯到哪里
String str = "ababaa";
char[] chars = str.toCharArray();
int next[] = new int[chars.length];
int i = 0;
int j = -1;
next[0] = -1;
while (i < chars.length - 1){
if (j == -1 || chars[i] == chars[j]){
++j;
++i;
next[i] = j;
}else {
j = next[j];
}
}
System.out.println(next);
图解:
