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 <string.h>
char s1[1000002], s2[1000002];
int next[1000002];
int main()
{
int i,j, m, n, k, x;
while(scanf("%s",s1)!=EOF)
{
scanf("%s",s2);
k=0;
j=-1;
next[0] = -1;
m=strlen(s1);
n=strlen(s2);
while(k < n)
{
if (j == -1 || s2[k] == s2[j])
{
++k;
++j;
next[k] = j;
}
else
j = next[j];
}
i=0;
j=0;
x=0;
while(i<m&&j<n)
{
if(s1[i]==s2[j])
{
i++;
j++;
}
else
{
if(next[j]==-1)
{
j=0;
i++;
x=i;
}
else
{
j=next[j];
x=i-j;
}
}
}
if(j>=n)
printf("%d\n",x+1);
else
printf("-1\n");
}
return 0;
}