求KMP算法的实现C或C++程序与KMP算法中求NEXT【】的C或C++程序
求KMP算法的实现C或C++程序与KMP算法中求NEXT【】的C或C++程序,求高手帮忙,先谢谢啦
#include<stdio.h>
#include<string.h>
#define NOTFOUND -1
#define ERROR -2
#define MAXLEN 100
char S[MAXLEN+10],T[MAXLEN+10],st[MAXLEN+10];
int S0,T0;
int pos;
int next[MAXLEN+10];
void Init(char *S,int &S0)
{
int len,i;
New_Input:
scanf("%s",st);
len=strlen(st);
if (len>MAXLEN)
{
printf("This String is too long,Please Input a new one.\n\n");
goto New_Input;
}
for (i=1;i<=len;i++) S[i]=st[i-1];
S[len+1]='\0';
S0=len;
}
void Get_next(char *S,int *next)
{
int i=1,j=0;
next[1]=0;
while (i<T0)
if (j==0 || T[i]==T[j])
{i++; j++; next[i]=next[j];}
else j=next[j];
}
int Index_KMP(char *S,char *T,int pos)
{
int i=pos,j=1;
while (i<=S0 && j<=T0)
if (j==0 || S[i]==T[j])
{i++; j++;}
else j=next[j];
if (j>T0) return i-T0;
else return NOTFOUND;
}
int main()
{
int ret;//函数返回值
Init(S,S0);
Init(T,T0);
scanf("%d",&pos);
Get_next(T,next);
ret=Index_KMP(S,T,pos);
if (ret==NOTFOUND) printf("Not Found.\n");
else if (ret==ERROR) printf("The Input Data is Error.\n");
else printf("In S,from %dth is equal to T.\n",ret);
return 0;
}