-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathknuth-Morris-Pratt-algorithm.cpp
64 lines (52 loc) · 1.12 KB
/
knuth-Morris-Pratt-algorithm.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
57
58
59
60
61
62
63
64
#include <iostream>
#include <ostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
void prefix_function(std::string s, std::vector<int> &pi) {
int m = (int)s.length();
pi[0] = 0;
for (int i = 1; i < m; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j]) {
j = pi[j - 1];
}
if (s[i] == s[j]) {
j++;
}
pi[i] = j;
}
}
int main(int argc, const char **argv) {
std::string T = "ABCABCDABABCDABCDABDEABCDABDABCDABD", p = "ABCDABD";
int n = (int)T.length(), m = (int)p.length();
std::vector<int> pi(m);
prefix_function(p, pi);
for (int l = 0; l < m; l++) {
std::cout << pi[l] << '\t';
}
std::cout << std::endl;
for (int i = 0; i < m; i++) {
std::cout << p[i] << '\t';
}
std::cout << std::endl;
int i = 0, j = 0;
while (i < n) {
if (p[j] == T[i]) {
i++;
j++;
}
if (j == m) {
std::cout << "Found pattern at " << i - j << std::endl;
j = pi[j - 1];
} else if (i < n && p[j] != T[i]) {
if (j != 0) {
j = pi[j - 1];
} else {
i = i + 1;
}
}
}
return 0;
}