首页 > 其他 > 详细

【模板】KMP

时间:2018-08-11 15:07:48      阅读:130      评论:0      收藏:0      [点我收藏+]

题意简述

给出两个字符串s1和s2,其中s2为s1的子串,求出s2在s1中所有出现的位置。

代码

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int nxt[1000010];
char st1[1000010], st2[1000010];
void cnxt(char* st, int l)
{
    int x = -1;
    nxt[0] = -1;
    for (register int i = 1; i < l; ++i)
    {
        while (x > -1 && st[i] != st[x + 1]) x = nxt[x];
        if (st[i] == st[x + 1]) ++x;
        nxt[i] = x;
    }
}
void kmp(char* st1, int l1, char* st2, int l2)
{
    int x = -1;
    cnxt(st2, l2);
    for (register int i = 0; i < l1; ++i)
    {
        while (x > -1 && st1[i]!=st2[x + 1]) x = nxt[x];
        if (st1[i] == st2[x + 1]) ++x;
        if (x == l2 - 1) printf("%d\n", i - l2 + 2);
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin >> st1 >> st2;
    kmp(st1, strlen(st1), st2, strlen(st2));
}

【模板】KMP

原文:https://www.cnblogs.com/xuyixuan/p/9459714.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!