SCU - 4438 Censor (KMP)

这是一个关于字符串处理的问题,要求帮助编辑 frog 删除文本中出现的第一个敏感词。输入包括模式串 w 和文本串 p,你需要实现 KMP 算法来找到并移除第一个匹配的敏感词,输出处理后的文本。题目保证了 w 和 p 的长度不超过 500 万,并且仅包含小写字母。提供的样例展示了如何应用 KMP 算法来解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值