Censor
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 wand 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,pconsists 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
题意:
把主串中的含子串的消除,然后合并,再消除,最后输出结果
思路:
先用KMP算法查到匹配的子串(每查找到一次匹配入栈),当全部匹配时出栈子串的数量,即消除了匹配的字符。
最后反向输出消除后的字符串。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
#include<cmath>
using namespace std;
char a[5000005],b[5000005];
int Next[5000005];//next编译错误
struct node{
char ch;
int pos;
}p;
void get_next(){
int i=0,j=-1,len=strlen(a);
Next[0]=-1;
while(i<len){
if(j==-1||a[i]==a[j]) Next[++i]=++j;
else j=Next[j];
}
}
void KMP(){
get_next();
int len1=strlen(a),len2=strlen(b);
int i=0,j=0;
if(len1>len2){
printf("%s\n",b);
return;
}
stack<node>q;
while(i<len2){
if(j==-1 || a[j]==b[i]){//成功匹配
p.ch=b[i];
p.pos=j;
q.push(p);
i++,j++;
}
else j=Next[j];
if(j>=len1){
int t=len1;
while(t--)q.pop();
if(q.empty())j=0;
else j=q.top().pos+1;
}
}
stack<node>qq;
while(!q.empty()){
qq.push(q.top());
q.pop();
}
while(!qq.empty()){
printf("%c",qq.top());
qq.pop();
}
printf("\n");
}
int main(){
while(~scanf("%s %s",a,b))
KMP();
return 0;
}