public class Next {
static void getNext(String P, int next[]) {
// j的意义是失配的位置
// k的意义是p0p1..pk
/**
* 012
* aac
* aab
* 这是时候失配的位置在2,j=2
*/
int j = 0, k = -1;
next[0] = -1;
while (j < P.length() - 1) {
// 如果出现不匹配的情况,回溯去求p0p1...pk的最长相等前后缀(取个名叫K1),并另此次的最长相等前后缀等于(K1)
if (k >= 0 && P.charAt(j) != P.charAt(k)) {
k = next[k];
} else {
j++;
k++;
if (P.charAt(j) == P.charAt(k))
next[j] = next[k];
else
next[j] = k;
}
}
}
static int fastFind(String T, String P, int next[]) {
int j = 0, i = 0;
while (j < P.length() && i < T.length())
if (j == -1 || P.charAt(j) == T.charAt(i)) {
j++;
i++;
} else
j = next[j];
if (j < P.length())
return -1;
else
return i - P.length();
}
public static void main(String[] args) {
String T = "aaaaaacdaxue";
String P = "aac";
int[] next = new int[P.length()];
Next.getNext(P, next);
int success = Next.fastFind(T, P, next);
// for (int i : next) {
// System.out.println(i);
// }
System.out.println(success);
//结果:4
//注:开始索引是0
}
}
06-12