【题目链接】
https://www.lydsy.com/JudgeOnline/problem.php?id=3942
【算法】
栈 + KMP
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 1000010 int i,pos,top,ls,lt; int nxt[MAXN],p[MAXN]; char S[MAXN],T[MAXN],ans[MAXN]; int stk[MAXN]; int main() { scanf("%s%s",S+1,T+1); ls = strlen(S+1); lt = strlen(T+1); for (i = 2; i <= lt; i++) { pos = nxt[i-1]; while (pos && T[pos+1] != T[i]) pos = nxt[pos]; if (T[pos+1] == T[i]) pos++; nxt[i] = pos; } for (i = 1; i <= ls; i++) { if (!top) { if (S[i] == T[1]) stk[++top] = 1; else stk[++top] = 0; p[top] = i; } else { pos = stk[top]; while (pos && T[pos+1] != S[i]) pos = nxt[pos]; if (T[pos+1] == S[i]) pos++; stk[++top] = pos; p[top] = i; if (pos == lt) top -= lt; } } for (i = 1; i <= top; i++) putchar(S[p[i]]); printf(" "); return 0; }