KMP简单应用
Time Limit: 1000MS Memory limit: 65536K
题目描述
给定两个字符串string1和string2,判断string2是否为string1的子串。
输入
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
输出
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
示例输入
abc a 123456 45 abc ddd
示例输出
1 4 -1
#include <stdio.h> #include <stdlib.h> #include <string.h> char s[1100000],t[1100000]; int next[1100000]; void Next() { int i,j; i=0; j=-1; next[0]=-1; int len1=strlen(t); while(i<len1) { if(j==-1||t[i]==t[j]) { ++i; ++j; next[i]=j; } else j=next[j]; } } int KMP(int le1,int le2) { int i,j; Next(); i=0; j=0; while(i<le1&&j<le2) { if(j==-1||s[i]==t[j]) { ++i; ++j; } else j=next[j]; } //printf("%d %d\n",i,j); if(j>=le2) { return i-le2+1; } return -1; } int main() { int i,j,e,n,m; while(scanf("%s",s) != EOF) { scanf("%s", t); int le_2=strlen(t); int le_1=strlen(s); e=KMP(le_1,le_2); printf("%d\n",e); } return 0; }