KMP模板

#include <cstdio>
#include <algorithm>
#include <string>
#include <iostream>

#define MAXN 1000006

std::string pat,txt;
int pre[MAXN];

int main() {

    std::ios::sync_with_stdio(0);
    std::cin.tie(0); std::cout.tie(0);

    std::cin >> txt >> pat;
    int len_1 = txt.length(),len_2 = pat.length();
    txt = ' ' + txt; pat = ' ' + pat;//防止出现-1

    pre[1] = 0; int len = 0;
    for(int i=1;i<len_2;++i) { //从1开始 pre[1]一定为0,计算完成
        while(pat[i+1]!=pat[len+1]&&len>0) len = pre[len];
        if(pat[i+1]==pat[len+1]) ++len;
        pre[i+1] = len;
    }

    len = 0;
    for(int i=0;i<len_1;++i) { // 从0开始
        while(txt[i+1]!=pat[len+1]&&len>0) len = pre[len];
        if(txt[i+1]==pat[len+1]) ++len;
        if(len==len_2) {
            printf("%d\n",(i+1)-len+1);
            len = pre[len];
        }
    }

    for(int i=1;i<=len_2;++i) printf("%d ",pre[i]);

    return 0;
}
上一篇:Kmp


下一篇:459. 重复的子字符串(KMP算法)