forked from deepaktalwardt/interview-prep-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknuth-morris-pratt-algorithm.cpp
More file actions
50 lines (46 loc) · 876 Bytes
/
knuth-morris-pratt-algorithm.cpp
File metadata and controls
50 lines (46 loc) · 876 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
49
50
#include <vector>
using namespace std;
vector<int> buildPattern(string str) {
int n = str.size();
if (n == 1) return {-1};
int i = 1;
int j = 0;
vector<int> pattern(n, -1);
while (i < n) {
if (str[i] == str[j]) {
pattern[i] = j;
i++;
j++;
} else {
if (j != 0) {
j = pattern[j - 1] + 1;
} else {
i++;
}
}
}
return pattern;
}
bool doesMatch(string str, string substr, vector<int>& pattern) {
int i = 0;
int j = 0;
while (i + substr.size() - j <= str.size()) {
if (str[i] == substr[j]) {
if (j == substr.size() - 1) return true;
i++;
j++;
} else {
if (j != 0) {
j = pattern[j - 1] + 1;
} else {
i++;
}
}
}
return false;
}
bool knuthMorrisPrattAlgorithm(string str, string substr) {
// Write your code here.
vector<int> pattern = buildPattern(substr);
return doesMatch(str, substr, pattern);
}