KMP的应用

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的思维先找到标准的字符串temp的next数组;
然后去进行查找;并删除;(有点小技巧;应该是kmp中有过的);

一;找next数组;就是套用并查集模板

void cp()//并查集找next数组 
{
    next[0] = next[1] = 0;
    int k = 0;
    int len =strlen(temp);
    for(int i = 2; i<len; i++)
    {
        while(k != 0 && temp[k] != temp[i-1]) 
            k = next[k];
        if(temp[k] == temp[i-1])    k++;
        next[i] = k;
    }
}

二;进行删除比较操作;

        cp();
        len1 = strlen(temp);
        len2 = strlen(str);
        k = 0; j = 0;
        for(i = 0; i < len2; i++,k++)
        {
            ans[k] = str[i];//ans的作用就是保存str被删除后的字符;
                            //这样i可以一直i++不用管删除; 
            while(j>0 && temp[j]!=str[i]) j = next[j];//这个与并查集的作用一样;找到前面那个匹配的地方; 
            if(temp[j] == str[i]) j++;//2时候执行;1j=0并且他们相等则要加1;2;下个又相等;则要加一 
            if(j == len1)//实现减去相同部分 
            {
                k -= len1;
                j = p[k];
            }
            ans[k+1] = 0;
            p[k] = j;//记录每次的j值; 
        }

j的作用;指向temp的位置;
ans数组的作用;保存str中被删除后的字符并直须更新;
k的作用;实际移动的指向;对str;
i就是一直递增;对str;
p数组;保存对temp的next类似;

感觉还是不能使用kmp的那种思维;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值