KMP算法
1 void Next(char *src,int n,int *next) 2 { 3 int j,k; 4 j=0; 5 k=-1; 6 next[0] = -1; 7 while(j<n-1) 8 { 9 if(k==-1 || src[j] == src[k]) 10 { 11 ++k;++j; 12 next[j] = k; 13 } 14 else 15 k=next[k]; 16 } 17 } 18 19 int KMP(char *des,int n ,char *src,int m) 20 { 21 assert(des != NULL && src !=NULL && n>0 && m>0); 22 23 char *pdes=des; 24 char *psrc=src; 25 26 int i=0,j=0; 27 int *next = (int *)malloc(m*sizeof(int)); 28 Next(src,m,next); 29 for(int k = 0;k<m;k++) 30 printf("%d ",next[k]); 31 printf("\n"); 32 33 while(j<m && i<n) 34 { 35 if(j==-1 || psrc[j] == pdes[i]) 36 { 37 ++i;++j; 38 } 39 else 40 { 41 j=next[j]; 42 } 43 } 44 if(j<m) 45 return -1; 46 else 47 return i-j; 48 }
BF算法
1 int BF(const char *des,const char *src) 2 { 3 assert(des != NULL && src != NULL); 4 int i,j; 5 int len_1 = strlen(des); 6 int len_2 = strlen(src); 7 if(len_1 < len_2) 8 return -1; 9 for(i = 0;i<=len_1-len_2;i++) 10 { 11 for(j=0;j<len_2;j++) 12 { 13 if(des[i+j] != src[j]) 14 break; 15 } 16 if(j==len_2) 17 return i; 18 } 19 return -1; 20 }