0%

单词替换

题意

给出一个只包含小写字母的s字符串,和单词A,B。把s中的所有A替换成B,长度都小于5e6。PS:这题不需要考虑后效性

分析

1.这题就是最裸的KMP,当s中匹配到A的时候把匹配到A的首位置标记一下,输出的时候直接跳过lenA的长度同时输出B就好

思考

1.用KMP的时候一定要统一模板,以后就决定用f[0] = 0, f[1] = 0,这样的方式了,不需要纠结,也就不会有分歧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*************************************************************************
> File Name: b.cpp
> Author: liangxianfeng
> Mail: 641587852@qq.com
> Created Time: 2016年05月02日 星期一 20时41分52秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<string>
#include<cmath>
using namespace std;
#define ll long long
#define rep(i,n) for(int i =0; i < n; ++i)
#define CLR(x) memset(x,0,sizeof x)
#define MEM(a,b) memset(a,b,sizeof a)
#define pr(x) cout << #x << " = " << x << " ";
#define prln(x) cout << #x << " = " << x << endl;
const int maxn = 5e6+100;
const int INF = 0x3f3f3f3f;
char s[maxn], t[maxn], ss[maxn];
int fs[maxn];
int lent, lens, lenss;
void getfail(char *str, int *fail){
fail[0] = 0;
fail[1] = 0;
int j = 0;
for(int i = 1; i < lens; ++i){
j = fail[i];
while(j && str[i] != str[j]) j = fail[j];
fail[i+1] = (str[i] == str[j]?j+1:0);
}
}
void find(char *T, char *S, int *fail){
int j = 0;
for(int i = 0; i < lent; ++i){
while(j && T[i] != S[j]) j = fail[j];
if(T[i] == S[j]) ++j;
if(j == lens){
T[i-lens+1] = 0;
j = 0;
}
}
}
void printT(char* T, char* b){
for(int i = 0; i < lent; ++i){
if(T[i] == 0){
printf("%s", b);
i+=lens-1;
} else printf("%c", T[i]);
}
printf("\n");
}
int main(){
#ifdef LOCAL
freopen("/home/zeroxf/桌面/in.txt","r",stdin);
//freopen("/home/zeroxf/桌面/out.txt","w",stdout);
#endif
int kase;
scanf("%d", &kase);
while(kase--){
scanf("%s%s%s", t, s, ss);
lent = strlen(t);
lens = strlen(s);
lenss = strlen(ss);
getfail(s, fs);
find(t, s, fs);
printT(t, ss);
}
return 0;
}