[模板] KMP算法

fail 失配数组 fail[i]表示以i为结尾的非前缀子串与s的前缀的最大匹配长度
在拼接两字符串后,求fail数组的同时就能求出匹配位置(fail[i]==len_origin的i-2*len_origin)

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int MAXN=2200002;

char s[MAXN],tmp[MAXN];
int fail[MAXN];

int olen,lens;

int main(){
    scanf("%s%s",tmp+1,s+1);
    olen=strlen(s+1);
    strcat(s+1,".");
    strcat(s+1,tmp+1);
    lens=strlen(s+1);
    for(int i=2,j=0;i<=lens;i++){
        while(j>0&&s[i]!=s[j+1]) j=fail[j];
        if(s[i]==s[j+1]) j++;
        fail[i]=j;
        if(j==olen) cout<<i-olen-olen<<endl;
    }
    for(int i=1;i<=olen;i++) cout<<fail[i]<<" ";

    return 0;
}

 长大了,改了一下

#include<bits/stdc++.h>

using namespace std;

const int MAXN = 1000005;

char s[MAXN],t[MAXN];
int fail[MAXN];

int main(){
    scanf("%s",t+1);
    scanf("%s",s+1);
    int lens=strlen(s+1);
    int lent=strlen(t+1);
    for(int i=2,j=0;i<=lens;i++){
        while(j>0&&s[j+1]!=s[i])j=fail[j];
        if(s[j+1]==s[i]) j++;
        fail[i]=j;
    }
    for(int i=1,j=0;i<=lent;i++){
        while(j>0&&t[i]!=s[j+1]) j=fail[j];
        if(t[i]==s[j+1]) j++;
        if(j==lens) cout<<i-j+1<<endl;    
    }
    for(int i=1;i<=lens;i++) cout<<fail[i]<<" ";
}

本文来自博客园,作者:GhostCai,转载请注明原文链接:https://www.cnblogs.com/ghostcai/p/9247463.html

原文地址:https://www.cnblogs.com/ghostcai/p/9247463.html