Description
给出两个字符串 S 和 T,每次从前往后找到 S 的一个子串A=T 并将其删除,空缺位依次向前补齐,重复上述操作多次,直到 S 串中不含 T 串。输出最终的 S 串。
Input
第一行包含一个字符串 S,第二行包含一个字符串 T。
Output
输出处理后的 S 串。
whatthemomooofun moo
-
Sample Input
whatthefun
-
Sample Output
HINT
对于全部数据,1≤∣T∣≤∣S∣≤10^6,保证字符串中只出现小写字母。
Source/Category
另外弱化版 https://blog.csdn.net/drtlstf/article/details/87915491
这里可以发现判断栈顶是否存在目标串时效率太慢,于是可以用KMP优化。
文本串的结果也压倒一个栈里
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
const int MAXN = 1000010;
int c[MAXN], nxt[MAXN], id[MAXN];
int main() {
string a, b; cin >> a >> b;
int top = 0, sa = a.size(), sb = b.size();
nxt[0] = -1;
for (int i=1; i<sb; ++i) { // 自己匹配自己求nxt
int j = nxt[i-1];
while ((j!=-1) && (b[j+1]!=b[i])) j = nxt[j];
if (b[j+1]==b[i]) ++j;
nxt[i] = j;
}
int j = -1;
for (int i=0; i<sa; ++i) {
c[++top] = a[i]; // 压入
while ((j!=-1) && (b[j+1]!=c[top])) j = nxt[j]; // 匹配过程
if (b[j+1]==c[top]) ++j;
id[top] = j; // 存储匹配长度
if (j+1==sb) j = id[top-=sb]; // 匹配成功,出栈
}
for (int i=1; i<=top; ++i) printf("%c", c[i]);
return 0;
}