题解 P4824 【[USACO15FEB]Censoring S】

· · 题解

介绍一种简单的方法,不用KMP、AC自动机、线段树、Hash······

纯暴力解决(虽然有点慢)

代码奉上(仅17行,注释在代码里)

#include <iostream>
#include <cstring>
using namespace std;
char s[1000005],t[105],r[1000005];
int main(){
    cin>>s+1>>t+1;//读入两个字符串
    int sc=strlen(s+1),tc=strlen(t+1);//测长
    int j=0;
    for(int i=1;i<=sc;i++){
        r[++j]=s[i];//将s串中字符依次加入r串 
        r[j+1]='\0';//手动加'\0' 
        if(j>=tc&&strcmp(r+j-tc+1,t+1)==0)//r的后缀串与t相同 
        j=j-tc;//删除r串后strlen(t)个字符 
        r[j+1]='\0';//手动加'\0' 
    }
    cout<<r+1;//输出r串 
}