SCU - 4438 Censor (KMP)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chimchim04/article/details/89492658

Censor

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

She has a long text pp. Her job is relatively simple -- just to find the first occurence of sensitive word ww 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 11 string ww. The second line contains 11 string pp.

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

Output

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

Sample Input

    abc
    aaabcbc
    b
    bbb
    abc
    ab

Sample Output

    a
    
    ab

题目大意:给出模式串和文本串,每次删掉文本串中出现的第一个模式串,直到文本串中没有模式串

思路:字符串匹配可以用KMP或者字符串Hash解决

KMP的解题思路: 先求出模式串的next数组,在比较的时候把字符压进栈中,当匹配到模式串的时候,把匹配到的模式串出栈,再继续往下比较,最后栈中剩下的字符就是答案

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stack>
using namespace std;
const int N=5000005;
char s[N],p[N],ans[N];
int nex[N],n,m;
struct node
{
    char a; //字符
    int k;  //当前字符与模式串匹配到的位置
    node(){}
    node(char _a,int _k){a=_a,k=_k;}
};
void getnext()  //求nex数组
{
    int i=-1,j=0;
    nex[0]=-1;
    while(j<m)
    {
        if(i==-1||s[i]==s[j]) nex[++j]=++i;
        else i=nex[i];
    }
}
void kmp() 
{
    stack<node>sta;
    int i=0,j=0;
    while(i<n)
    {
        if(j==-1||p[i]==s[j])
        {
            i++,j++;
            sta.push(node(p[i-1],j)); //把字符和,匹配位置入栈
        }
        else  j=nex[j];
        if(j==m)   //匹配到模式串,把串出栈
        {
            int k=m;
            while(k--) sta.pop();
            if(sta.empty()) j=0;
            else j=sta.top().k;
        }
    }
    int k=0;
    while(!sta.empty())
        ans[k++]=sta.top().a,sta.pop();
    for(int i=k-1;i>=0;i--) printf("%c",ans[i]);
    printf("\n");
}
int main()
{
    while(~scanf("%s%s",s,p))
    {
        n=strlen(p),m=strlen(s);
        getnext();
        kmp();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chimchim04/article/details/89492658
kmp