核心思想:找副串的最长公共子串
目的
为了找到最长公共子串的后一位,将副串后移,避免副串一位一位移
找到副串每一位的最长子串,生成最长子串表
匹配主串
发现不同
后移p串
代码
public static int KMP(String str1, String str2) {
if (str1.length() < str2.length()) {
return -1;
}
int next[] = 部分匹配表(str2);
for (int i = 0, j = 0; i < str1.length();) {
while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
j = next[j - 1];
}
if (str1.charAt(i) == str2.charAt(j)) {
j++;
}
i++;
if (j == str2.length()) {
return i - j;
}
}
return -1;
}
public static int[] 部分匹配表(String str) {
int[] result = new int[str.length()];
result[0] = 0;
for (int i = 1, j = 0; i < str.length(); i++) {
while (j > 0 && str.charAt(i) != str.charAt(j)) {
j = result[j - 1];
}
if (str.charAt(i) == str.charAt(j)) {
j++;
}
result[i] = j;
}
return result;
}