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 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 1string 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
#include<bits/stdc++.h>
using namespace std;
const int maxn=5e6+10;
char str[maxn],s[maxn];
struct node{
char ch;
int val;
node(){}
node(char _ch,int _val):ch(_ch),val(_val){}
};
node stk[maxn];
int top;
int f[maxn];
/*
模式串和文本串的比较
abc
aaabcbabccc
还是比较难受的,当时只是想到了栈这个数据结构,但是没有想到kmp,来匹配
导致匹配一直出现问题,还是做的少啊
*/
void solve(int l1,int l2){
top=-1;
int j=0;
for(int i=0;i<l2;i++){
if(top==-1)j=0;
else j=stk[top].val;
while(j&&str[i]!=s[j])j=f[j];
if(str[i]==s[j])j++;
stk[++top]=node(str[i],j);
if(j==l1){
top-=l1;
}
}
}
void get_f(int l){
f[0]=f[1]=0;
for(int i=1;i<l;i++){
int j=f[i];
while(j&&s[i]!=s[j])j=f[j];
f[i+1]=s[i]==s[j]?j+1:0;
}
}
int main()
{
while(scanf("%s %s",s,str)==2){
int len1=strlen(s),len2=strlen(str);
if(len1>len2){
printf("%s\n",str);
continue;
}
get_f(len1);
solve(len1,len2);
for(int i=0;i<=top;i++)printf("%c",stk[i].ch);
printf("\n");
}
return 0;
}
#include<bits/stdc++.h>
#define lowbit(x) (x&(-x))
#define rep(i,a,b) for(int i=a;i<b;i++)
using namespace std;
const int maxn=5e6+10;
char str[maxn],p[maxn];
int fail[maxn];
void getFail(char* p,int len){
fail[0]=fail[1]=0;
for(int i=1;i<len;i++){
int j=fail[i];
while(j&&p[i]!=p[j])j=fail[j];
fail[i+1]=(p[i]==p[j]?j+1:0);//在J指向i+1的时候,[0,i]文本后缀和模版前缀匹配的长度,也就是J在i+1失配的时候要转移的位置
}
}
int stk_fail[maxn];
char stk[maxn];
void solve(int len,int m){
int top=0;
int j=0;
stk_fail[0]=0;
for(int i=0;i<len;i++){
stk[top]=str[i];//将字符压入栈顶
while(j&&p[j]!=str[i])j=fail[j];
if(p[j]==str[i])++j;
stk_fail[++top]=j;
if(j==m){//如果说匹配的长度,已经到了m,说明可以减掉了
top-=m;
j=stk_fail[top];
}
}
for(int i=0;i<top;i++)printf("%c",stk[i]);
printf("\n");
}
/*
abc
aaabcbc
b
bbb
abc
ab
*/
int main()
{
while(scanf("%s %s",p,str)==2){
int len=strlen(str),m=strlen(p);
getFail(p,m);
solve(len,m);
}
return 0;
}