KMP算法利用之前判断过信息,通过一个next数组,保存模式串中前后最长公共子序列的长度,每次回溯时,通过next数组找到,前面匹配过的位置,省区了大量的计算时间。
import java.util.Arrays;
public class KMPAlgorithm {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1 = "BBC ABCDAB ABCDABCDABDE";
String str2 = "ABCDABD";
int[] next = kmpNext("ABCDABD");
System.out.println(Arrays.toString(next));
int index = kmpSearch(str1, str2, next);
System.out.println(index);
}
// kmp搜索算法
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;
}
// 获取到一个字符串(字串)的部分匹配值
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++) {
// 当dest.charAt(i)!=dest.charAt(j),我们需要从next[j-1]获取新的j
// 直到发现有dest.charAt(i)==dest.charAt(j)成立才退出
while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
j = next[j - 1];
}
// 当dest.charAt(i)==dest.charAt(j)满足时,部分匹配值就是+1
if (dest.charAt(i) == dest.charAt(j)) {
j++;
}
next[i] = j;
}
return next;
}
}