-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.cpp
More file actions
48 lines (44 loc) · 716 Bytes
/
tools.cpp
File metadata and controls
48 lines (44 loc) · 716 Bytes
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
#include "tools.h"
void getnext(string tgt, vector<int>& next) {
int k = -1;
int j = 0;
next[0] = -1;
while (j < tgt.size()) {
if (k == -1 || tgt[k] == tgt[j]) {
if (tgt[++k] == tgt[++j]) {
next[j] = next[k];
}
else {
next[j] = k;
}
}
else {
k = next[k];
}
}
}
void replacekmp(string& str, string& src, string& tgt) {
vector<int> next(src.size() + 1, 0);
getnext(src, next);
int i = 0;
int j = 0;
while (i < str.size()) {
if (j == -1) {
j = 0;
i++;
}
else {
if (str[i] == src[j]) {
++i;
++j;
if (j == src.size()) {
str = str.substr(0, i - src.size()) + tgt + str.substr(i);
return;
}
}
else {
j = next[j];
}
}
}
}