SCU-4438 Censor(字符串HASH)

本文介绍了一个使用哈希算法处理敏感词删除的问题。通过计算敏感词的哈希值,并利用栈来辅助处理文本中的匹配和删除过程,实现了高效的文本过滤。


哈希模板:挑战程序设计P374


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


题意:每次删去字符串b中的a串,输出最终剩余的字符


思路: 将a串哈希为一个整数,将b字符依次放入栈中,当长度大于等于a串的长度时,比较哈希值,相同则删除,继续操作


CODE:

#include<stdio.h>
#include<vector>
#include<iostream>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
typedef unsigned long long ull;
const ull B =1e8+7;//哈希的基数  
const int N=5*1e6+10;
ull bh[N];
char a[N],b[N],str[N];
int main()
{
    while(~scanf("%s%s",a,b))
    {
        int a1=strlen(a),b1=strlen(b);
        if(a1>b1)
        {
            printf("%s\n",b);
            continue;
        }
        ull t=1;
       for(int i=0; i<a1; i++)
        {
             t*=B;
        }
        ull ah=0;
        bh[0]=0;
        for(int i=0; i<a1; i++) ah=ah*B+a[i];
      //  printf("%llu \n",ah);
        int top=0;
        for(int i=0;i<b1;i++)
        {
            str[top++]=b[i];
            bh[top]=bh[top-1]*B+b[i];
            
            if(top>=a1&&bh[top]-bh[top-a1]*t==ah)
            {
                //printf("%d\n",top);
                top-=a1;
            }

        }
       for(int i=0;i<top;i++)
       {
           printf("%c",str[i]);
       }
       printf("\n");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值