#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
void Next(char *src,int n,int *next)
{
int j,k;
j=0;
k=-1;
next[0] = -1;
while(j<n-1)
{
if(k==-1 || src[j] == src[k])
{
++k;++j;
next[j] = k;
}
else
k=next[k];
}
}
int KMP(char *des,int n ,char *src,int m)
{
assert(des != NULL && src !=NULL && n>0 && m>0);
char *pdes=des;
char *psrc=src;
int i=0,j=0;
int *next = (int *)malloc(m*sizeof(int));
Next(src,m,next);
for(int k = 0;k<m;k++)
printf(“%d “,next[k]);
printf(“\n”);
while(j<m && i<n)
{
if(j==-1 || psrc[j] == pdes[i])
{
++i;++j;
}
else
{
j=next[j];
}
}
if(j<m)
return -1;
else
return i-j;
}
int main()
{
char des[] = “acabaabaabcacx”;
char src[] = “abaabcac”;
printf(“%d\n”,KMP(des,14,src,8));
return 0;
}