Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。(string1和string2大小不超过100字符)
Output
对于每组输入数据,若string2是string1的子串,则输出"YES",否则输出"NO"。
Example Input
abc a 123456 45 abc ddd
Example Output
YES YES NO
Author
赵利强
#include <bits/stdc++.h>
using namespace std;
char st1[1000001],st2[1000001];
int next[1000001];
void get_next()
{
int i=0,j=-1,k;
next[0]=-1;
while(st2[i]!='\0')
{
if(j==-1||st2[i]==st2[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void kmp()
{
int i=0,j=0,k;
get_next();
int len1=strlen(st1);
int len2=strlen(st2);
while(i<len1&&j<len2)
{
if(j==-1||st1[i]==st2[j])
{
i++;
j++;
}
else
j=next[j];
}
if(j>=len2)
{
cout<<"YES"<<endl;
}
else
cout<<"NO"<<endl;
}
int main()
{
while(cin>>st1>>st2)
{
kmp();
}
return 0;
}