-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathKMP.cpp
45 lines (42 loc) · 997 Bytes
/
KMP.cpp
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
template <typename T>
vector<int> kmp_table(int n, const T &s) {
vector<int> p(n, 0);
int k = 0;
for (int i = 1; i < n; i++) {
while (k > 0 && !(s[i] == s[k])) {
k = p[k - 1];
}
if (s[i] == s[k]) {
k++;
}
p[i] = k;
}
return p;
}
template <typename T>
vector<int> kmp_table(const T &s) {
return kmp_table((int) s.size(), s);
}
template <typename T>
vector<int> kmp_search(int n, const T &s, int m, const T &w, const vector<int> &p) {
assert(n >= 1 && (int) p.size() == n);
vector<int> res;
int k = 0;
for (int i = 0; i < m; i++) {
while (k > 0 && (k == n || !(w[i] == s[k]))) {
k = p[k - 1];
}
if (w[i] == s[k]) {
k++;
}
if (k == n) {
res.push_back(i - n + 1);
}
}
return res;
// returns 0-indexed positions of occurrences of s in w
}
template <typename T>
vector<int> kmp_search(const T &s, const T &w, const vector<int> &p) {
return kmp_search((int) s.size(), s, (int) w.size(), w, p);
}