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;
}