码迷,mamicode.com
首页 > 其他好文 > 详细

Censoring(栈+KMP)

时间:2018-09-08 22:37:05      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:pac   href   class   \n   print   turn   scan   std   main   

# 10048. 「一本通 2.2 练习 4」Censoring

【题目描述】

给出两个字符串 $S$ 和 $T$,每次从前往后找到 $S$ 的一个子串 $A=T$ 并将其删除,空缺位依次向前补齐,重复上述操作多次,直到 $S$ 串中不含 $T$ 串。输出最终的 $S$ 串。

【算法】

1、kmp $O(n)$就可以定位。
2、栈是个好东西啊。
注:一开始想双指针,实在不好写。。。栈很好,它可以弹出去。。。(此处滑稽脸)

【代码】

#include <bits/stdc++.h>
using namespace std;
int l1,l2,top;
int nxt[1000100],f[1000100];
char s[1000100],t[1000100],ans[1000100];
void parse() {
    nxt[1]=0;
    for(int i=2,j=0;i<=l2;i++) {
        while(j>0&&(j==l2||t[i]!=t[j+1])) j=nxt[j];
        if(t[i]==t[j+1]) j++;
        nxt[i]=j;
    }
}
int main() {
    scanf("%s%s",s+1,t+1);
    l1=strlen(s+1),l2=strlen(t+1);
    parse();
    for(int i=1,j=0;i<=l1;i++) {
        ans[++top]=s[i];
        while(j>0&&(j==l2||s[i]!=t[j+1])) j=nxt[j];
        if(s[i]==t[j+1]) j++;
        f[top]=j;
        if(j==l2) {
            top-=l2;
            j=f[top];
        }
    }
    ans[++top]='\0';
    printf("%s\n",ans+1);
    return 0;
}

Censoring(栈+KMP)

标签:pac   href   class   \n   print   turn   scan   std   main   

原文地址:https://www.cnblogs.com/Willendless/p/9610642.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!