Java实现KMP算法
- KMP 算法就利用之前判断过信息, 通过一个 next 数组, 保存模式串中前后最长公共子序列的长度, 每次回溯时, 通过 next 数组找到, 前面匹配过的位置, 省去了大量的计算时间。
- KMP算法核心之一是部分匹配表,部分匹配” 的实质是, 有时候, 字符串头部和尾部会有重复。 比如, ” ABCDAB” 之中有两个” AB” , 那么它的” 部分匹配值” 就是 2(” AB” 的长度) 。 搜索词移动的时候, 第一个” AB” 向后移动 4 位(字符串长度-部分匹配值) , 就可以来到第二个” AB” 的位置。
/**
* kmp查找算法
* @param str1 源字符串
* @param str2 子串
* @param next 部分匹配表
* @return 成功返回子串开始的下标,失败返回-1
*/
public static int kmpSearch(String str1, String str2, int[] next) {
for (int i = 0, j = 0; i < str1.length(); i ++) {
while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
j = next[j - 1];
}
if (str1.charAt(i) == str2.charAt(j)) {
j ++;
}
if (j == str2.length()) {
return i - j + 1;
}
}
return -1;
}
/**
* 部分匹配表
* @param str 子串
* @return 返回部分匹配表
*/
public static int[] kmpNext(String str) {
int[] next = new int[str.length()];
next[0] = 0;
for (int i = 1, j = 0; i < str.length(); i ++) {
while (j > 0 && str.charAt(i) != str.charAt(j)) {
j = next[j - 1];
}
if (str.charAt(i) == str.charAt(j)) {
j ++;
}
next[i] = j;
}
return next;
}