码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-06-24 00:46:28      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:cin   include   string   ble   code   main   ace   串匹配   https   

题目链接: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;
}

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

标签:cin   include   string   ble   code   main   ace   串匹配   https   

原文地址:https://www.cnblogs.com/MisakaAzusa/p/9218941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!