这两天读了JULY的KMP,觉得很受益,写下以作备忘。
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int * getNext(const char *str2){ //求出next数组
int pLen = strlen(str2);
int *next = (int *)malloc(sizeof(int)*pLen);
next[0] = -1;
int k = -1;
int j = 0;
while( j<= pLen-2 ){
if( k==-1 || str2[k]==str2[j] ){
++k;
++j;
next[j] = k; //出现相等即求出了包括str2[j] 在内的最长前缀后缀的长度
}
else{
k = next[k]; //不相等则继续进行递推
}
}
return next;
}
int KMP_sarch(const char *str1,const char *str2){
int i = 0,j = 0;
int len1 = strlen(str1);
int len2 = strlen(str2);
int * next;
next = getNext(str2);
while(i<len1&&j<len2){
if( j==-1 || str1[i]==str2[j] ){
i++;
j++;
}
else{
j = next[j];
}
}
free(next); //释放next数组
if( j==len2 ){
return i-j;
}
else{
return -1;
}
}
int main(int argc,char *argv[]){
char *str1="BBC ABCDAB ABCDABCDABDE";
char *str2="ABCDABD";
printf("%d\n",KMP_sarch(str1,str2));
return 0;
}