KMP模板

#include<bits/stdc++.h>
using namespace  std;
#define ll long long
#define pb push_back
#define inf 200000099999999
#define mod 998244353
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define rep1(i,a,b) for(int i=a;i>=b;i--)
const int N=1e3+100;
string str1,str;
int ne[N],n,m,cnt;
struct node
{
    int l,r;
}app[N];
void kmpnext()
{
    ne[0] = -1;
    int k = -1;
    for (int q = 1; q <= m-1; q++)
    {
        while (k > -1 && str[k + 1] != str[q])
        {
            k = ne[k];
        }
        if (str[k + 1] == str[q])
        {
            k = k + 1;
        }
        ne[q] = k;
    }
}
int KMP()
{
    kmpnext();
    int k = -1;
    for (int i = 0; i < n; i++)
    {
        while (k >-1&& str[k + 1] != str1[i])
            k = ne[k];
        if (str[k + 1] == str1[i])
            k = k + 1;
        if (k == m-1)
        {
            k = -1;
            i = i - m + 1;
        }
    }
    return -1;
}
int main()
{
    ios::sync_with_stdio(0);
    cnt=0;
    int q;
    cin>>n>>m>>q;
    cin>>str1>>str;
    KMP();

    return 0;
}
posted @ 2018-08-04 08:53  ffgcc  阅读(84)  评论(0编辑  收藏  举报