//KMP algorithm Ye Zhuang
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char str1[501];
char str2[501];
int next[501];
gets(str1);
gets(str2);
int x,y,i,j;
x = strlen(str1);
y = strlen(str2);
i = 0;
j = -1;
next[0] = -1;
// 背+以ab-cccccc-ab为例理解
while(i<y-1)
{
if(j==-1||str2[i]==str2[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
// get next[]
i = 0;
j = 0;
while(i<x&&j<y)
{
if (j == -1 || str1[i]==str2[j])
{
i++;
j++;
}
else
j = next[j];
}
if(j==y)
printf("%d",i-j+1);
else
printf("No!");
// match orperation
return 0;
}
算法笔记7.KMP算法
于 2021-02-22 15:36:15 首次发布