字符串匹配--KMP算法

来源:互联网 发布:淘宝客采集软件有哪些 编辑:程序博客网 时间:2024/06/08 20:12

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-1)    {        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;    }}
原创粉丝点击