#include <stdio.h>
#include <string.h>
int KMP(char *t, char *p, int *next) {
int a,i,j;
a=0; i=0; j=0;
while(i<strlen(t) && a<strlen(p))
if (t[i]==p[a]) { a++; i++; }
else
if (a!=0) a=next[a] ;
else i++;
if (a==strlen(p)) return i-a+1 ;
else return -1;
}
void c_next(char *p, int *next){/*?????£ê?′?μ?next*/
int i,j,k;
next[0]=-1;i=1; k=-1;
while (i<=strlen(p))
if ((k==-1)||(p[i-1]==p[k])){next[i]=k+1; k++; i++; }
else k=next[k];
}
void printC(char *p){ /*′òó?×?·?′?*/
int i;
for (i=0; i<strlen(p); i++) printf("%2c",p[i]);
}
void printN(int *p, int Len){ /*ó?óú′òó?nextêy×éμ??μ*/
int i;
for (i=0; i<Len; i++) printf("%2d",p[i]);
}
void printSpace(int len){ /*′òó?????£???DDoó?é??D§1?*/
int i;
for (i=1; i<=len; i++)printf(" ");
}
main(){
int i, next[20];
/*char *t,*p;/*×¢£o′????úTurboc2?D?yè·£??úCFree?¢CodeBlockμè?·?3?D?á3?????DDê±′í?ó*/
char t[20],p[20]; /*′????úTurboc2?¢CFree?¢CodeBlockμè?·?3?D?ù?yè·*/
printf("\n please input text string: ");
gets(t);
printf("\n please input pattern string: ");
gets(p);
c_next(p,next);
i=KMP(t,p,next);
printf("\n");
printC(t); printf("\n");
printSpace(2*i-2); printC(p); printf("\n");
printSpace(2*i-2); printN(next, strlen(p));
printf("\n the result is %d", i);
}