-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmp.cpp
56 lines (47 loc) · 826 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
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <vector>
using namespace std;
vector<int> getLps(string pattern) {
int m = pattern.length();
vector<int> lps(m, 0);
int i = 1, j = 0;
while (i < m) {
if (pattern[i] == pattern[j]) {
lps[i] = 1 + j;
++i; ++j;
} else {
if (j == 0) {
lps[i] = 0;
++i;
} else {
j = lps[j - 1];
}
}
}
return lps;
}
void kmp(string text, string pattern) {
vector<int> lps = getLps(pattern);
int i = 0, j = 0;
while (i < text.length()) {
if (text[i] == pattern[j]) {
++i; ++j;
} else {
if (j == 0) {
++i;
} else {
j = lps[j - 1];
}
}
if (j == pattern.length()) {
cout << i - j << " ";
j = lps[j - 1];
}
}
}
int main() {
string text = "this is very misti";
string pattern = "is"; // 2, 5, 14
kmp(text, pattern);
return 0;
}