-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch_pattern_kmp.h
More file actions
57 lines (46 loc) · 1.23 KB
/
Copy pathsearch_pattern_kmp.h
File metadata and controls
57 lines (46 loc) · 1.23 KB
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
#ifndef SEARCH_SEARCH_PATTERN_KMP_H_
#define SEARCH_SEARCH_PATTERN_KMP_H_
#include <vector>
using namespace std;
inline vector<int> createPrefixArray(const vector<int>& pattern) {
vector<int> prefix(pattern.size(), -1);
int i = 0;
int j = 1;
while (j < pattern.size()) {
if (pattern[i] == pattern[j]) {
// We have a match, thus prefix = suffix.
prefix[j] = i;
++j;
++i;
} else if (i > 0) {
// No match but we are in string, thus we reset to the last pattern.
i = prefix[i - 1] + 1;
} else {
// I is anyways already at beginnning, thus no need to reset.
++j;
}
}
return prefix;
}
inline int searchPatternKmp(
const vector<int>& data, const vector<int>& pattern) {
const vector<int> prefix = createPrefixArray(pattern);
int pattern_idx = 0;
int data_idx = 0;
while (data_idx < data.size()) {
if (data[data_idx] == pattern[pattern_idx]) {
if (pattern_idx == pattern.size() - 1) {
return true;
} else {
++data_idx;
++pattern_idx;
}
} else if (pattern_idx > 0) {
pattern_idx = prefix[pattern_idx - 1] + 1;
} else {
++data_idx;
}
}
return false;
}
#endif // SEARCH_SEARCH_PATTERN_KMP_H_