概述
这里仅仅做一个笔记,我将用 java 实现一个常见的 kmp 算法版本,关于该算法的讲解和理解,大家可以移步去该专栏 – 如何更好地理解和掌握 KMP 算法?,上面已经有很多前辈讲解的很透彻了。
算法实现
public class KMPTest {
// test
public static void main(String[] args) {
String haystack = "aaabbababcabaaaabb", needle = "ababcabaa";
int res = kmp(haystack, needle);
// 返回子串在主串中的索引
System.out.println(res);
}
// 匹配主串的主逻辑
public static int kmp(String haystack, String needle) {
if (needle == null || needle.length() == 0)
return 0;
if (haystack == null || haystack.length() == 0)
return -1;
int[] next = new int[needle.length()];
int i = 0, j = 0;
getNext(needle, next);
// System.out.println(Arrays.toString(next));
while (i < haystack.length()) {
if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
if (j == needle.length())
return i-j;
}
return -1;
}
// 整个算法的关键在于 Next 数组的生成
public static void getNext(String needle, int[] next) {
int i = 0, j = -1;
next[0] = -1;
while (i < needle.length()-1) {
if (j == -1 || needle.charAt(i) == needle.charAt(j)) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
}
总结
不忘初心,砥砺前行!