kmp()

#include
using namespace std;
//#define int long long
const int N=5e5+10;
int n,m;string s,p;
int nex[N];
void getnext(string s)
{
    int j=-1;
    nex[0]=j;
    for(int i=1;i     {
        while(j>=0&&s[i]!=s[j+1])
        {
            j=nex[j];
        }
        if(s[i]==s[j+1])
        {
            j++;
        }
        nex[i]=j;
    }
}
int kmp(string s,string p)
{
    
    int j=-1;
    int n=s.size();
    for(int i=0;i     {
        while(j>=0&&s[i]!=p[j+1])
        {
            j=nex[j];
        }
        if(j==-1)
        {
            if(s[i]!=p[j+1])
            {
                return -1;
            }
        }
        if(s[i]==p[j+1])
        {
            j++;
        }
        if(j==p.size()-1)
        {
            j=nex[j];
        }
    }
    return 1;
}
signed main()
{
    ios::sync_with_stdio(false), cin.tie(0);
    int t;
    cin>>t;
    while(t--)
    {    
        cin>>s>>p;getnext(s);
        if(kmp(p,s)==1)
        {
            printf("Yes\n");
        }
        else
        {
            printf("No\n");
        }        
    }

}

你可能感兴趣的:(c++,图论,算法)