-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_algorithms.cpp
More file actions
37 lines (35 loc) · 972 Bytes
/
string_algorithms.cpp
File metadata and controls
37 lines (35 loc) · 972 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
vector<size_t> zFunction(const string& str) {
vector<size_t> z(str.size(), 0);
size_t left = 0, right = 0;
for (size_t i = 1; i < str.size(); ++i) {
if (right <= i) {
left = right = i;
} else {
if (z[i - left] < right - i) {
z[i] = z[i - left];
continue;
} else {
z[i] = right - i;
left = i;
}
}
while (right < str.size() && str[i + z[left]] == str[z[left]]) {
++z[left];
++right;
}
}
return z;
}
vector<int> prefixFunction(const string& str) {
vector<int> result(str.size(), 0);
for (size_t i = 1; i < str.size(); ++i) {
int prefix = result[i - 1];
for (; str[prefix] != str[i]; prefix = result[prefix]) {
--prefix;
if (prefix < 0)
break;
}
result[i] = prefix + 1;
}
return result;
}