题目:https://pintia.cn/problem-sets/1268384564738605056/problems/1296272390837731328
题解:https://blog.csdn.net/weixin_44260779/article/details/102613232
代码:

#include<iostream>
using namespace std;
int Next[100005]={0};
void GetNext(string a)
{
    int len=a.length();
    int i=0;
    int j=-1;
    Next[0]=-1;
     while(i<len-1)
    {
        if(j==-1||a[i]==a[j])
        {
            i++;
            j++;
            Next[i]=j;
        }else
            j=-1;
    }
}
int kmp(string a,string b)
{
    GetNext(b);
    int i=0;//a
    int j=0;//b
    int len1=a.length();
    int len2=b.length();
    while(i<len1&&j<len2)
    {
        if(j==-1||a[i]==b[j])
        {
            i++;
            j++;
        }else
            j=Next[j];
    }
    if(j==len2)
    return i-j;
    return -1;
}
int main()
{
    string a,b;
    int n;
    cin>>a;
    cin>>n;
    while(n--)
    {
        cin>>b;
        int index=kmp(a,b);
        if(index!=-1)
        cout<<a.substr(index)<<endl;
        else
        cout<<"Not Found"<<endl;
    }
    return 0;
}

 

 posted on 2020-09-05 22:55  邢涌芝  阅读(148)  评论(0编辑  收藏  举报