//这是第一次实现KMP算法
#include<stdio.h>
#define MAXLEN 50
#include<string.h>
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++;
if (s[k] == s[j])
next[j] = next[k];
else
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 (strings[i] == pattern[j])
{
i++;
j++;
}
else if (strings[i] != pattern[j] && j == 0)
{
i++;
}
else
{
j = next[j];
}
}
if (pattern[j] == ‘\0’)
printf("%d\n", i - lenpatt);
else
printf(“not found\n”);
return 0;
}