#include<stdio.h>
#include<malloc.h>
int next[50];
void get_next(char *T,int *next)//求模式串的next数组
{
int i=1,j=0;
next[1]=0;//由定义知
while(i<T[0])
{
if(j==0||T[i]==T[j])
{
++i;
++j;
next[i]=j;
}
else
{
j=next[j];
}
}
}
int Index_KMP(char *S,char *T,int pos)
{
int i=pos;
int j=1;
while(i<=S[0]&&j<=T[0])
{
if(j==0||S[i]==T[j])
{
++i;
++j;
}
else
{
j=next[j];
}
}
if(j>T[0])
return i-T[0];
else
return 0;
}
int main(int argc,char *argv[])
{
char *S=(char*)malloc(sizeof(char)*256);
char *T=(char*)malloc(sizeof(char)*25);
printf("请输入源字符串的长度\n");
scanf("%d",&S[0]);//注意不超过255
printf("请输入源字符串\n");
scanf("%s",S+1);
printf("请输入模式串的长度\n");
scanf("%d",&T[0]);
printf("请输入模式串\n");
scanf("%s",T+1);
get_next(T,next);
printf("%d\n",Index_KMP(S,T,1));
return 0;
}