Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
Output
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
Example Input
abc a 123456 45 abc ddd
Example Output
1 4 -1
#include <bits/stdc++.h>
using namespace std;
int next[60];
char a[60], b[60];
void nexta()
{
int i = 0, j = -1;
next[0] = -1;
while(b[i]!='\0')
{
if(j==-1||b[i]==b[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
void kmp(int x, int y)
{
nexta();
int i = 0, j = 0;
while(i<x && j<y)
{
if(j==-1 || a[i]==b[j])
{
i++, j++;
}
else
j = next[j];
}
if(j>=y)
{
printf("%d\n", i-j+1);
}
else
printf("-1\n");
}
int main(int argc, char **argv)
{
while(1)
{
gets(a);
gets(b);
int x = strlen(a);
int y = strlen(b);
kmp(x, y);
}
return 0;
}