kmp算法适合大字符串的对比匹配
kmp 核心,获取模式串回溯索引数组
private static int[] getNext(String needle) {
int length = needle.length();
char[] chars = needle.toCharArray();
int [] next = new int[length];
// 初始化查找字符串索引数组,没有上级映射为-1
next[0] = -1;
int pre = -1;
int i = 0;
while (i < length - 1) {
if (pre == -1 || chars[pre] == chars[i]) {
next[++i] = ++pre;
// 优化 当下一组索引对比也相同,当前索引取上一组索引的值
if (chars[i] == chars[pre]) {
next[i] = next[pre];
}
} else {
pre = next[pre];
}
}
return next;
}
字符串对比
// kmp算法 查找字符串
public static int kmpIndexOf(String haystack, String needle) {
if (needle.length() == 0) {
return 0;
}
char[] h = haystack.toCharArray();
int hl = haystack.length();
char[] n = needle.toCharArray();
int nl = needle.length();
int[] next = getNext(needle);
//开始匹配
// 主串位置
int i = 0;
// 模式串位置
int j = 0;
while (i < hl && j < nl) {
if (j == -1 || h[i] == n[j]) {
i++;
j++;
} else {
// 模式串回溯
j = next[j];
}
}
// 匹配成功
if (j >= nl) {
return i - nl;
}
// 匹配失败
return -1;
}