#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void GetNext(int *next,char *s2,int len2)
{
int j=-1;
int i=0;
next[0]=-1;
while(i<len2-1)
{
if(j==-1||s2[i]==s2[j])
{
i++;
j++;
if(s2[i]!=s2[j])
next[i]=j;
else
next[i]=next[j];
}
else
j=next[j];
}
}
int KMP(char *s1,int len1,char *s2,int len2)
{
int i=0,j=0;
int index;
int *next=(int *)malloc(len2*sizeof(int));
GetNext(next,s2,len2);
while(i<len1&&j<len2)
{
if(j==-1||s1[i]==s2[j])
{
i++;
j++;
}
else
j=next[j];
}
int k;
for(k=0;k<len2;k++)
printf("%d,",next[k]);
free(next);
if(j>=len2)
return i-len2;
else
return -1;
}
int main()
{
FILE *fin=fopen("test.in","r");
FILE *fout=stdout;
int len1,len2;
char *s1=(char*)malloc(sizeof(char)*200);
char *s2=(char*)malloc(sizeof(char)*200);
fscanf(fin,"%s",s1);
fscanf(fin,"%s",s2);
len1=strlen(s1);
len2=strlen(s2);
fprintf(fout,"%d\n",KMP(s1,len1,s2,len2));
return 0;
}
KMP(Knuth、Morris和Partt) 线性时间字符串匹配算法
最新推荐文章于 2024-02-20 10:20:42 发布