Censor (kmp)

本文介绍了一种利用KMP算法实现的文本敏感词过滤方法,通过预先处理子串构建next数组来提高匹配效率,避免了传统方法中大量无效的回溯。该算法在面对大规模文本和频繁出现的敏感词时,表现出较高的处理速度。

思路:关键是用一个数组记录母串中当前所指字符与子串相匹配字符的长度。kmp思想,当母串中出现一次子串时,j跳到子串pos[i-len2]的位置接着与母串i所指的下一个字符比较。

(wawawawawawaac大哭)

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.

(1length of w,p51061≤length of w,p≤5⋅106w,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

#include<iostream>

#include<cstring>

#include<string>
#include<cstdio>
using namespace std;
const int maxn=5000005;
char s1[maxn],s2[maxn];
int pos[maxn];
int nextt[maxn];
char las[maxn];
int len1,len2 ;
using namespace std;

void GetNext()
{ int i=0,j=-1;
    nextt[0]=-1;
    while(s2[i]!='\0')
    {
        if(j==-1 || s2[i]==s2[j])
        {
            i++;
            j++;
        nextt[i]=j;
        }
        else
            j=nextt[j];
    }
}
int main()
{

    while(~scanf("%s %s",s2,s1))//s2 子串,s1 母串

    {
        len1 = strlen(s1);
        len2 = strlen(s2);
        GetNext();
        int k=0;
        int i=0;
        int j=0;
        while(i < len1)
        {
            las[k]=s1[i];
            while(j!=-1 && las[k]!=s2[j])
                j=nextt[j];
            i++;
            j++;
            pos[k++]=j;   //记录匹配到k位置时对应的成功匹配到了的子串字符数目.
            if(j==len2)
            {
                k-=len2;  //相当于删除。
                j=pos[k-1];  子串跳转的位置。
            }
        }
        las[k] = '\0';
        printf("%s\n",las);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值