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

【模板】KMP

时间:2018-08-11 15:32:47      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:++i   code   char   clu   space   syn   amp   mes   str   

题意简述

给出两个字符串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

标签:++i   code   char   clu   space   syn   amp   mes   str   

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

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