public class KMPTest {
public static void main(String[] args) {
String s = "abbabbbbcab"; // 主串
String t = "bbcab"; // 模式串
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
System.out.println(KMP_Index(ss, tt)); // KMP匹配字符串
}
public static int[] next(char[] t) {
int[] next = new int[t.length];
next[0] = -1;
int i = 0;
int j = -1;
while (i < t.length - 1) {
if (j == -1 || t[i] == t[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
return next;
}
public static int KMP_Index(char[] s, char[] t) {
int[] next = next(t);
int i = 0;
int j = 0;
while (i <= s.length - 1 && j <= t.length - 1) {
if (j == -1 || s[i] == t[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j < t.length) {
return -1; // fail
} else
return i - t.length; // success
}
}
KMP算法关键是当在某个位置出现不匹配的时候,目标串不回溯,模式串往后移动,相对来时就是滑动。如何计算next数组就是难点,只要领悟了它的设计思路,寻找到匹配下标index就很简单了。