-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStringPatternMatching.cpp
More file actions
60 lines (48 loc) · 1.18 KB
/
StringPatternMatching.cpp
File metadata and controls
60 lines (48 loc) · 1.18 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
58
59
60
//* KMP Algorithm (String Pattern Matching)
//* Efficient string search in O(n + m) time.
#include <iostream>
#include <vector>
using namespace std;
vector<int> computeLPS(string pattern) {
int m = pattern.size();
vector<int> lps(m, 0);
int len = 0, i = 1;
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len-1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
void KMP(string text, string pattern) {
int n = text.size();
int m = pattern.size();
vector<int> lps = computeLPS(pattern);
int i = 0, j = 0;
while (i < n) {
if (text[i] == pattern[j]) {
i++; j++;
}
if (j == m) {
cout << "Pattern found at index " << i - j << endl;
j = lps[j-1];
} else if (i < n && text[i] != pattern[j]) {
if (j != 0) j = lps[j-1];
else i++;
}
}
}
int main() {
string text = "ABABDABACDABABCABAB";
string pattern = "ABABCABAB";
KMP(text, pattern);
}