// KMP算法
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void get_next(char *T,int next[]) //修正前的next数组
{
int i = 1,j = 0;
next[0] = -1;
next[1] = 0;
int m = strlen(T);
while(i<strlen(T)-1)
{
if(j == -1||T[j]==T[i])
{
++i;
++j;
next[i] = j;
}
else j = next[j];
}
}
void get_nextval(char *T,int nextval[]) //修正后的nextval数组
{
int i = 1,j = 0;
nextval[0] = -1;
nextval[1] = 0;
int m = strlen(T);
while(i<strlen(T)-1)
{
if(j == -1||T[j]==T[i])
{
++i;
++j;
if(T[i]!=T[j])
nextval[i] = j;
else nextval[i] = nextval[j];
}
else j = nextval[j];
}
}
int Index_kmp(char *S,char *T,int pos,int next[]) //逐项比较
{
int j = 0,i = pos,len1=strlen(S),len2=strlen(T);
get_next(T,next);
while(i<len1&&j<len2)
{
if(S[i]==T[j]||j==-1)
{
i++;j++;
}
else j = next[j];
}
if(j>=len2) return i-len2;
else return -1;
}
int main()
{
char *S="aab",*T="ab";
int m;
int *next = (int *)malloc((strlen(T)+1)*sizeof(int)); //修正前的next数组
int *nextval = (int *)malloc((strlen(T)+1)*sizeof(int)); //修正后的nextval数组
get_next(T,next);
printf("nextarray:");
for(m = 0;m<strlen(T);m++)
{
printf("%d ",next[m]+1);
}
get_nextval(T,nextval);
printf("\n nextvalue:");
for(m=0;m<strlen(T);m++)
{
printf("%d ",nextval[m]+1);
}
int t = Index_kmp(S,T,0,nextval);
if(t==-1) printf("\n not match!\n");
else
{
printf("\n at the %d match\n",t+1);
}
return 0;
}
void get_next(char *T,int next[]) //修正前的next数组
{
int i = 1,j = 0;//i是后缀,j是前缀,i比j大
next[0] = -1;
next[1] = 0;
int m = strlen(T);
while(i<strlen(T)-1)
{
if(j == 0||T[i]==T[j])//i的值为3,j的是1 j=0,从第一个进去
{
++i;//i的值为4
++j;//j的值为2
next[i] = j;//next[i]的值为2
}
else j = next[j];//回溯 在4这里失配,找4的next的值,next[4]=2,把2对应的下标又是4,j等于4
}
}
next数组详解