【luogu P3375 KMP字符串匹配】 模板

题目链接:https://www.luogu.org/problemnew/show/P3375
实际上KMP是一种自己匹配自己的模式。好好理解qaq

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000001;
char a[maxn], b[maxn];
int next[maxn], lena, lenb;
int main()
{
    cin>>a>>b;
    next[0] = -1;
    next[1] = 0;
    int lenb = strlen(b); int lena = strlen(a);
    int j = 0;
    for(int i = 1; i < lenb; i++)
    {
        while(j>0 && b[j] != b[i]) j = next[j];
        if(b[j] == b[i]) ++j;
        next[i+1] = j;
    }
    j = 0;
    for(int i = 0; i < lena; i++)
    {
        while(j>0 && b[j] != a[i]) j = next[j];
        if(b[j] == a[i]) ++j;
        if(j == lenb)
        {
            printf("%d\n",i-lenb+2);
            j = next[j];
        }
    }
    for(int i = 1; i <= lenb; i++)
    printf("%d ",next[i]);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/MisakaAzusa/p/9218941.html