1. 程式人生 > >KMP演算法(C語言)

KMP演算法(C語言)

#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Êý×éµÄÖµ*/
   int i;
   for (i=0; i<Len; i++) printf("%2d",p[i]);
}
void printSpace(int len){ /*´òÓ¡¿Õ¸ñ£¬ÔËÐкó¿É¼ûЧ¹û*/
  int i;
  for (i=1; i<=len; i++)printf(" ");
}
main(){
   int i, next[20];
   /*char *t,*p;/*×¢£º´Ë¾äÔÚTurboc2ÖÐÕýÈ·£¬ÔÚCFree¡¢CodeBlockµÈ»·¾³Öлá³öÏÖÔËÐÐʱ´íÎó*/
   char t[20],p[20]; /*´Ë¾äÔÚTurboc2¡¢CFree¡¢CodeBlockµÈ»·¾³ÖоùÕýÈ·*/
   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);


}