kmp算法精髓就是降低了复杂度,如果是长度m的字符串,查找有没有长度为n的字符串,用暴力算法需要执行m*n次运算。
kmp在找到next数组后,可以只遍历一遍长度为n的字符串,就能得到结果。
生成next数组和最终遍历字符串n的逻辑是一样的,生成next数组,我看了好几个人的视频,文章最后我放上我认为讲的清楚的大佬视频的链接。
因为今天比较困,就不写我自己的推导过程了,后续有时间,一定会画图补上的。
public class Kmp0422 {
public static void main(String[] args) {
String str2 = "sadasdaabaacfgasdasda";
String str = "aabaacfg";
char[] chars = str.toCharArray();
int[] next = getNext(chars);
int j = 0;
for (int i = 0; i < str2.length(); i++) {
char cValue = str2.charAt(i);
while (j > 0 && cValue != chars[j]) {
j = next[j - 1];
}
if (cValue == chars[j]) {
j++;
}
if (j == chars.length) {
int index = i - j + 1;
System.out.println("匹配到了,开始下标为:" + index + ",匹配的首字母是:" + str2.charAt(index));
return;
}
}
System.out.println("很遗憾,没有匹配到字符串");
}
private static int[] getNext(char[] chars) {
// 初始化
int[] next = new int[chars.length];
int j = 0;
for (int i = 1; i < chars.length; i++) {
// 不相等
while (j > 0 && chars[i] != chars[j]) {
j = next[j - 1];
}
// 相等
if (chars[i] == chars[j]) {
j++;
}
// 赋值
next[i] = j;
}
return next;
}
}
生成next的四步,来自己这位大佬的视频
https://www.bilibili.com/video/BV1M5411j7Xx/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=457798b5bca8ebcd5484725ff7d3d1dd
,
下面这个视频是主打动态视频的,动态的可以看出kmp是怎么运行的,方便理解
https://www.bilibili.com/video/BV1AY4y157yL/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=457798b5bca8ebcd5484725ff7d3d1dd