SCU 4438 Censor(KMP / HASH)

过滤敏感词

其实就是找子串  就是记录答案的时候不一样

用一个类似于栈的容器记录已经匹配过的就行了   遇到匹配成功的出栈n个就行了

KMP 为了出栈后能继续之前的匹配  多一个数组记录栈中当前元素的失配位置   -  -

KMP:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e6+10;
struct KMP
{
    int f[MAXN];
    void getFail(char S[])
    {
        int i=0,j=-1;
        int len=strlen(S);
        f[0]=-1;
        while (i<len)
        {
            if (j==-1||S[i]==S[j])
            {
                i++,j++;
                f[i]=j;
            }
            else
                j=f[j];
        }
    }
    ///Whether S is a substring of T
    ///Or whether T has S;
    int jmp[MAXN];
    char ans[MAXN];
    int beat(char T[],char S[])
    {
        int i=0,j=0,top=0;
        int n=strlen(T);
        int m=strlen(S);
        getFail(S);
        for(i=0;i<n;i++)
        {
            while(j!=-1&&T[i]!=S[j])
            {
                int t=j-f[j];
                j=f[j];
            }
            j++;
            jmp[top]=j;
            ans[top]=T[i];
            ans[++top]=0;
            jmp[i]=j;
            if(j==m)
            {
                top-=m;
                ans[top]=0;
                j=jmp[top-1];
            }
        }
        puts(ans);
        return 0;
    }
}soul;

char s[MAXN],t[MAXN];

int main()
{
    while(scanf("%s%s",s,t)!=EOF)
        soul.beat(t,s);
    return 0;
}

HASH:

#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
const int MAXN  = 5e6+100;
const int SEED = 13331;

ULL ht[MAXN],hs;
ULL xl[MAXN];
char s[MAXN],t[MAXN],ans[MAXN];
int main()
{
    xl[0]=1;
    for(int i=1;i<MAXN;i++)
        xl[i]=xl[i-1]*SEED;
    while(scanf("%s%s",s,t)!=EOF)
    {
        int n=strlen(s);
        hs=0;
        for(int i=0;i<n;i++)
            hs=hs*SEED+s[i];
        int top=0;
        int m=strlen(t);
        ht[0]=0;
        for(int i=0;i<m;i++)
        {
            ans[top++]=t[i];
            ht[top]=ht[top-1]*SEED+t[i];
            if(top>=n&&ht[top]-ht[top-n]*xl[n]==hs)
                top-=n;
        }
        for(int i=0;i<top;i++)
            printf("%c",ans[i]);
        puts("");
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值