直接抄的武大李春葆老师的数据结构上的改进KMP
// return the first matching string2 in the string1
#include <stdio.h>
#include <string.h>
#define MaxSize 1000
typedef struct
{
char ch[MaxSize];
int len;
} SqString;
void GetNextval(SqString t,int nextval[])
{
int j=0,k=-1;
nextval[0]=-1;
while(j<t.len)
{
if((k==-1)||(t.ch[j]==t.ch[k]))
{
j++;
k++;
if(t.ch[j]!=t.ch[k]) nextval[j]=k;
else nextval[j]=nextval[k];
}
else k=nextval[k];
}
}
int KMP(SqString s,SqString t)
{
int nextval[MaxSize],i=0,j=0,v;
GetNextval(t,nextval);
while((i<s.len)&&(j<t.len))
{
if((j==-1)||(s.ch[i]==t.ch[j]))
{
i++;
j++;
}
else j=nextval[j];
}
if(j>=t.len) v=i-t.len;
else v=-1;
return(v);
}
int main()
{
// freopen("kmp.in","r",stdin);
// freopen("kmp.out","w",stdout);
SqString str1,str2;
gets(str1.ch);
str1.len=strlen(str1.ch);
gets(str2.ch);
str2.len=strlen(str2.ch);
printf("%dn",KMP(str1,str2));
return(0);
}