您的位置:首页 > 其它

字符串匹配--KMP算法

2017-09-27 19:49 302 查看
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

看了一天的KMP,对KMP算法可以说是相当无语了。。。

数据结构课本上的伪代码也是让人抓狂。。。

next数组干脆改名叫做torture数组吧!

好不容易A了一道KMP题,抓紧记录下来。。。(暂时仍对KMP理解不深刻,还是等到脑子清醒再重新梳理一遍吧)

#include<iostream>
#include<string>
using namespace std;
const int M=1e6+10;
void Getnext(string t,int next[])
{
int i=0,j=-1;
next[0]=-1;
int len=t.size();
while(i<len)
{
if(j==-1||t[i]==t[j])
{
next[++i]=++j;
if(t[i]==t[j])
next[i]=next[j];
}
else
j=next[j];
}
}
bool index_KMP(string s,string t,int next[])
{
int i=0,j=0;
int len1=s.size(),len2=t.size();
while(i<len1&&j<len2)
{
if(j==-1||s[i]==t[j])
{
i++;j++;
}
else
{
j=next[j];
}
}
if(j>=len2)
return true;
else
return false;
}
int main()
{
string s,t;
int i;
while(cin>>s)
{
int next[M+50]= {0};
cin>>t;
Getnext(t,next);
int flag=index_KMP(s,t,next);
if(flag==0)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: