2015 四川省赛 C Censor(哈希 | KMP)

模式串为子串

KMP

/*

@author : victor

*/

#include <bits/stdc++.h>
using namespace std;



typedef long long ll;
const int MAX = 5e6 + 7;

int next_[MAX];
char s1[MAX], s2[MAX], ans[MAX];
int pos[MAX];
int l1, l2, cnt;
 
void get_next(char x[],int m,int next_[])
{
    int i ,j;
    j = next_[0] = -1;
    i = 0; 
    while(i < m){
        while(-1!=j&&x[i]!=x[j]) j = next_[j];
        next_[++i] = ++j;
    }
}
 
void KMP(){
    int i = 0, j = 0;
    cnt = 0;
    while(s1[i] != '\0')
    {
        ans[cnt] = s1[i ++];
        while(!(j == -1 || ans[cnt] == s2[j]))
            j = next_[j];
        j ++;
        cnt ++;
        pos[cnt] = j;
        if(j >= l2)
        {
            cnt -= l2;
            j = pos[cnt];
        }
    }
}
 
int main()
{
    while(scanf("%s %s", s2, s1) != EOF)
    {
        l1 = strlen(s1);
        l2 = strlen(s2);
        get_next(s2,l2,next_);
        KMP();
        for(int i = 0; i < cnt; i++)
            printf("%c", ans[i]);
        printf("\n");
    }
}


  
//    A B C A B C A B C
// -1 0 0 0 1 2 3 4 5 6
//    A B C B C C B A C

 

posted @ 2019-08-06 21:41  DWVictor  阅读(242)  评论(0编辑  收藏  举报