弱校联萌十一大决战之强力热身 C. Censor (KMP + stack)

C. Censor
Time Limit: 2000msMemory Limit: 65536KB 64-bit integer IO format: %lld Java class name: Main
Submit Status
frog is now a editor to censor so-called sensitive words (敏感词).

She has a long text p. Her job is relatively simple -- just to find the first occurence of sensitive word w 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 1 string w. The second line contains 1 string p.

(1≤length of w,p≤5⋅106, w,p consists of only lowercase letter)
Output
For each test, write 1 string which denotes the censored text.
Sample Input
abc
aaabcbc
b
bbb
abc
ab
Sample Output
a

ab




解析:扫一遍文本串,在扫描的时候,跟模式串匹配,将文本串字符和匹配字符个数压入栈,当匹配字符个数等于模式串长度时,将栈顶与模式串匹配的所有字符弹出,重新从栈顶元素的匹配个数开始计算下一次匹配(因为前面字符已经匹配了)。文本串扫完时,栈内所剩即为结果




AC代码:

#include <bits/stdc++.h>
using namespace std;

const int maxn = 5000000 + 5;
char t[maxn], p[maxn];
int next[maxn];
char out[maxn];

struct Node{
    char c;
    int k;
};

void get_next(){
    int len = strlen(p);
    int j = 0, k = -1;
    next[0] = -1;
    while(j < len){
        if(k == -1 || p[j] == p[k]){
            j ++;
            k ++;
            next[j] = k;
        }
        else k = next[k];
    }
}

int kmp(){
    int len1 = strlen(t), len2 = strlen(p);
    int i = 0, j = 0;
    stack<Node> ans;
    while(i < len1){
        if(j == -1 || t[i] == p[j]){
            i ++;
            j ++;
            ans.push(Node{t[i-1], j});
        }
        else j = next[j];
        if(j == len2){    //匹配模式串
            int len = len2;
            while(len --) ans.pop();
            if(ans.empty()) j = 0;
            else j = ans.top().k;
        }
    }
    int cnt = 0;
    while(!ans.empty()){
        out[cnt ++] = ans.top().c;
        ans.pop();
    }
    for(int i=cnt-1; i>=0; i--) putchar(out[i]);
    puts("");
}

int main(){
    #ifdef sxk
        freopen("in.txt", "r", stdin);
    #endif // sxk

    while(scanf("%s%s", p, t) != EOF){
        get_next();
        kmp();
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值