HDU2203-亲和串-KMP模板题

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2203

其实这就是一道模板题。这个题目就只需要将第一串直接复制一份在其末尾就可以解决循环移位的所有情况。这里需要注意的就是提前判断模式串的长度大于匹配串的时候,无论怎么移位都是不可能匹配的,所以直接输出no,这样可以避免复制之后可能匹配的情况。

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
using namespace std;
string str,T;
int Next[100005];
void get_next()
{
    int m=T.size();
    int i=0,j=-1;
    Next[0]=-1;
    while(i<m){
        if( j==-1 || T[i]==T[j]){
            i++,j++;
            if(T[i]!=T[j]) Next[i]=j;
            else Next[i]=Next[j];
        }else{
            j=Next[j];
        }
    }
}
int KMP()
{
    int n=str.size(),m=T.size();
    int i=0,j=0;
    while(i<n){
        if(str[i]==T[j]){
            if(j==m-1) return 1;
            i++,j++;
        }else{
            j=Next[j];
            if(j==-1) i++,j=0;
        }
    }
    return 0;
}
int main()
{
    cin.sync_with_stdio(false);
    while(cin>>str>>T){
        get_next();
        if(T.size()>str.size()){ cout<<"no"<<endl;continue;}        //  如果第二串更长,那么直接就是no;
        str+=str;           //  直接复制接在末尾,便可以解决所有轮回的问题;
        if(KMP()) cout<<"yes"<<endl;
        else cout<<"no"<<endl;
    }
    return 0;
}


你可能感兴趣的:(KMP)