数据结构实验之串二:字符串匹配
Time Limit: 1000MS Memory limit: 65536K
题目描述
给定两个字符串string1和string2,判断string2是否为string1的子串。
输入
输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。(string1和string2大小不超过100字符)
输出
对于每组输入数据,若string2是string1的子串,则输出"YES",否则输出"NO"。
示例输入
abc a 123456 45 abc ddd
示例输出
YES YES NO
提示
原来的网上的代码做这个题都是用字符数组做的,我就用KMP做一遍
#include<bits/stdc++.h>
using namespace std;
void GetNext(string p,int next[])
{
int i=0,j=-1;
next[0]=-1;
int len2=p.size();
while(i<len2-1)
{
if(j==-1||p[i]==p[j])
{
next[++i]=++j;
}
else
j=next[j];
}
}
int KMP(string c1,string c2)
{
int len1=c1.size();
int len2=c2.size();
int i=0,j=0;
int next[500100];
memset(next,0,sizeof(next));
GetNext(c2,next);
while(i<len1&&j<len2)
{
if(j==-1||c1[i]==c2[j])
{
i++;
j++;
}
else
j=next[j];
}
if(j>=len2)
return i-len2+1;
else
return -1;
}
int main()
{
string c1;
string c2;
while(cin>>c1)
{
cin>>c2;
int f=KMP(c1,c2);
if(f==-1)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
return 0;
}