学习找部分匹配表也就是next函数的一点代码笔记:
public class KMPAlgorithm {
//测试
public static void main(String[] args) {
String str1 = "BBC ABCDAB ABCDABCDABDE";
String str2 = "ABCDABD";
int[] next = kmpNext(str2);
System.out.println("next=" + Arrays.toString(next));
int position = kmpSearch(str1, str2, next);
}
//写出我们的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++) {
//需要处理 str1.charAt(i) != str2.charAt(j), 去调整j的大小
//KMP算法核心点, 可以验证...
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()) {//找到了 // j = 3 i
return i - j + 1;
}
}
return -1;
}
//获取到一个字符串(子串) 的部分匹配值表
public static int[] kmpNext(String dest) {
//创建一个next 数组保存部分匹配值
int[] next = new int[dest.length()];
next[0] = 0; //如果字符串是长度为1 部分匹配值就是0
for (int i = 1, j = 0; i < dest.length(); i++) {
//首先明确 i指向尾巴 一直往后走 而j 看相等的情况 有不相等的j就往回走
//如果遇到连续相等 那么j连续相加表示匹配
//当dest.charAt(i) != dest.charAt(j) ,我们需要从next[j-1]获取新的j
//直到我们发现 有 dest.charAt(i) == dest.charAt(j)成立才退出
//这是kmp算法的核心点
//如果此时i和j处的字符不同 那么 就把j更新一下 回退!!
//next[j-1]给到j 使得j 回退 这个公式是用数学推导的 比较麻烦
int nonSense;
while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
j = next[j - 1];//j遇到不相同的字符时 回退
}
//当dest.charAt(i) == dest.charAt(j) 满足时,部分匹配值就是+1
if (dest.charAt(i) == dest.charAt(j)) {
j++;
}
//此时要么j为0 正好给到next[i] 说明i处为止 前缀和后缀没有公共部分 此时i处部分匹配值为0
//在之前j的基础上 每找到一个dest.charAt(i) == dest.charAt(j)时 j++
//此时把j给到next[i] 实现更新next[i] 作为i处的部分匹配值
next[i] = j;
}
return next;
}
}