-1
#include <stdio.h> #include <stdlib.h> #include<string.h> #define max 1000001 int l1,l2; int next[1000100]; char s1[1000001],s2[1000001]; void get_next(char s2[],int next[]) //求模式串T的next函数值并存入数组next中 { int i=1; next[1]=0; int j=0; l2=strlen(s2); while(i<l2) { if(j==0||s2[i]==s2[j]) { ++i;++j; next[i]=j; } else j=next[j]; } } void Index_KMP(char s1[],char s2[],int pos)//利用模式串T的next函数求T在主串S中第pos个字符之后的位置 { int i,j; l1=strlen(s1); l2=strlen(s2); i=pos;j=1; while(i<=l1-1&&j<=l2-1) { if(j==0||s1[i]==s2[j]) //继续比较后续字符 { ++i;++j; } else j=next[j]; //模式串向右移动 } if(j>l2-1) //匹配成功 printf("%d\n",i-l2+1); else //不成功; printf("-1\n"); } int main() { while(gets(s1)) { gets(s2); l1=strlen(s1); l2=strlen(s2); get_next(s2,next); Index_KMP(s1,s2,1); } return 0; }