#include<stdio.h>
#define MaxSize 255
typedef struct
{
char ch[MaxSize];
int length;
}SString;
void InitStr(SString &S)
{
S.ch[0]=' ';
S.length=0;
}
void StrCreate(SString &S,char a[])
{
int i=0,j=1;
while(a[i]!='\0')
{
S.ch[j++]=a[i++];
}
S.length=i;
}
void get_next(SString T,int next[]) //模式串右移位数
{
int i=1,j=0;
next[1]=0;
while(i<T.length)
{
if(j==0 || T.ch[i]==T.ch[j])
{
i++;j++;
next[i]=j;
}
else
j=next[j];
}
}
void get_nextval(SString T,int nextval[])
{
int i=1,j=0;
nextval[1]=0;
while(i<T.length)
{
if(j==0 || T.ch[i]==T.ch[j])
{
i++;j++;2
if(T.ch[i]!=T.ch[j])
nextval[i]=j;
else
nextval[i]=nextval[j];
}
else
j=nextval[j];
}
}
int Index_KMP(SString S,SString T) //2.KMP算法优化
{
int i=1,j=1;
int next[255];
get_nextval(T,next);
while(i<=S.length && j<=T.length)
{
if(j==0 || S.ch[i]==T.ch[j])
{
i++;j++;
}
else
j=next[j]; //模式串向后移动
}
if(j>T.length)
return i-T.length;
else
return 0;
}
void main()
{
SString S;
InitStr(S);
char a[]="abcdefg";
char b[]="bcd";
StrCreate(S,a);
SString T;
StrCreate(T,b);
printf("The T is Num %d in S\n",Index_KMP(S,T));
}