先放代码,对着代码来讲一讲(代码没加注释)
#include<iostream>
#include<string.h>
const int MAXLEN = 50;
int next[MAXLEN] = { 0 };
int nextval[MAXLEN] = { 0 };
void get_next(char s[],int lens)
{
int j = 0;
int k = -1;
next[j] = k;
while (j < lens-1)
{
if (k == -1 || s[j] == s[k])
{
k++;
j++;
next[j] = k;
}
else
k = next[k];
}
}
int main()
{
char strings[] = "hello worldolollo,I'm the king of the world,and you'll be die!";
char pattern[] = "olol";
int lens = strlen(strings);
int lenpatt = strlen(pattern);
get_next(pattern, lenpatt);
int i = 0, j = 0;
while (i < lens&&pattern[j]!='\0')
{
if (j == -1 || strings[i] == pattern[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (pattern[j] == '\0')
printf("%d\n", i - lenpatt);
else
printf("not found\n");
return 0;
}
1、kmp算法的核心就是减少不必要的回溯,也就是说,我们在匹配到中间某个字符发现失配的时候,不需要重头再来(回忆太累人了你说是吧),我们已经在过程中有了很多线索,这