SCU-4438 Censor(KMP算法)

来源:互联网 发布:海贼王887 知乎 编辑:程序博客网 时间:2024/06/08 08:30

Censor

frog is now a editor to censor so-called sensitive words (敏感词).

She has a long text p p. Her job is relatively simple -- just to find the first occurence of sensitive word w w and remove it.

frog repeats over and over again. Help her do the tedious work.

Input

The input consists of multiple tests. For each test:

The first line contains 1 1 string w w. The second line contains 1 1 string p p.

(1length of w,p510 6  1≤length of w,p≤5⋅106w,p w,p consists of only lowercase letter)

Output

For each test, write 1 1 string which denotes the censored text.

#include<cstdio>#include<algorithm>#include<string.h>#include<queue>#include<set>#include<functional>#include<iostream>#include<math.h>#include<vector>#include<string>#include<stdlib.h>using namespace std;const int maxn = 5e6 + 5;int Next[maxn],tmp[maxn];void makeNext(const char P[]){    int q,k;    int m=strlen(P);    memset(Next,0,sizeof(Next));    Next[0]=0;    for(q=1,k=0;q<m;++q){        while(k>0&&P[q]!=P[k])            k=Next[k-1];        if(P[q]==P[k]) k++;        Next[q]=k;    }}char st[maxn];int KMP(const char T[],const char P[]){    int n=strlen(T),m=strlen(P),q=0,index=0;    makeNext(P);    for(int i=0;i<n;i++){        st[index++]=T[i];//记录匹配失败的字符        while(q>0&&P[q]!=T[i])            q=Next[q-1];        if(P[q]==T[i]) q++;        tmp[index]=q;//记录第index个字符的部分匹配值        if(q==m) {            index-=m;//匹配成功时,删去最后m个字符,继续匹配            q=tmp[index];//将index的部分匹配值给q        }    }    return index;}char st1[maxn],st2[maxn];int main(){   // freopen("in.txt","r",stdin);    while(~scanf("%s%s",st1,st2)){        st[KMP(st2,st1)]='\0';        printf("%s\n",st);    }    return 0;}

Sample Input

    abc    aaabcbc    b    bbb    abc    ab

Sample Output

    a        ab
题意:给出2个字符串,第一个字符串P是第二个字符串的敏感词,如果第二个字符串出现了P就要删除,后面的字符补到前面去,问最后剩下的字符串是什么
题解:KMP算法,用数组模拟栈储存要输出的字符串,index表示单签储存了几个字符,如果遇到要删除的字符串,则index-P的长度,然后继续更新,关于KMP算法的
话,如果不懂就先网上搜索下资料吧,这个算法我还不能很好地总结.




0 0
原创粉丝点击