-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
46 lines (39 loc) · 1.05 KB
/
main.cpp
File metadata and controls
46 lines (39 loc) · 1.05 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
/*
Finds all occurrences of the pattern string p within the
text string t. Running time is O(n + m), where n and m are the lengths of p and t, respecitvely.
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef vector<int> VI;
void buildPi(string& p, VI& pi){
pi = VI(p.length());
int k = -2;
for(int i = 0; i < p.length(); i++) {
while(k >= -1 && p[k+1] != p[i])
k = (k == -1) ? -2 : pi[k];
pi[i] = ++k;
}
}
int KMP(string& t, string& p){
VI pi;
buildPi(p, pi); int k = -1;
for(int i = 0; i < t.length(); i++){
while(k >= -1 && p[k+1] != t[i]){
k =((k == -1) ? -2 : pi[k]);
k++;
}
if(k == p.length() - 1){
// p matches t[i-m+1, ..., i]
cout << "matched at index " << i-k << ": "; cout << t.substr(i-k, p.length()) << endl;
k = (k == -1) ? -2 : pi[k];
}
}
return 0;
}
int main(){
string a = "AABAACAADAABAABA", b = "AABA";
KMP(a, b); // expected matches at: 0, 9, 12
return 0;
}