KMP算法主要就是next数组的计算,核心就是利用已经匹配的字符串,不向暴力算法那样,要重头开始比较,具体理论参考这篇博文:http://blog.csdn.net/u012532559/article/details/44464441
下面就是实现代码:
public class TestKMP {
public static void main(String[] args) {
String original = "BBC ABCDAB ABCDABCDABDE";
String find = "ABCDABD";
System.out.println(KMP(original,find));
}
/**计算next数组
* @param ps 模式串
* @return
*/
public static int[] getNext(String ps) {
char[] p = ps.toCharArray();
int[] next = new int[p.length];
next[0] = -1;
int j = 0;
int k = -1;
while (j < p.length - 1) {
//p[j]表示后缀的单个字符,p[k]表示前缀的单个字符
if (k == -1 || p[j] == p[k]) {
if (p[++j] == p[++k]) { // 当两个字符相等时要跳过
// 如果与前缀字符相同,则将前缀字符的 nextval值赋值给nextval在j位置的值
next[j] = next[k];
} else {
next[j] = k; //若当前字符与前缀字符不同,则当前的k为nextval在j位置的值
}
} else {
k = next[k]; //若字符不相同,则k值回溯
}
}
return next;
}
/**
* @param ts 主串
* @param ps 模式串
* @return
*/
public static int KMP(String ts, String ps) {
char[] t = ts.toCharArray();
char[] p = ps.toCharArray();
int i = 0; // 主串的位置
int j = 0; // 模式串的位置
int[] next = getNext(ps);
while (i < t.length && j < p.length) {
// 当j为-1时表示字符串开始
if (j == -1 || t[i] == p[j]) {
i++;
j++;
} else {
// i不需要回溯了
// i = i - j + 1;
j = next[j]; // j回到指定位置
}
}
if (j == p.length) {
return i - j;
} else {
return -1;
}
}
}
本文详细介绍了KMP算法的核心思想及其应用,并提供了具体的Java实现代码。通过避免重复比较,KMP算法显著提高了字符串匹配效率。
1337

被折叠的 条评论
为什么被折叠?



