-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmp.cpp
58 lines (49 loc) · 1.12 KB
/
kmp.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
#include "kmp.h"
#include <iostream>
using namespace std;
KMP::KMP(const string& pattern) : pattern(pattern) {
buildLPS();
}
void KMP::buildLPS() {
int m = pattern.length();
lps.resize(m,0);
int len = 0;
int 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++;
}
}
}
}
vector<int> KMP::search(const string& text) {
vector<int> result;
int n = text.length();
int m = pattern.length();
int i = 0; //for text[]
int j = 0; //for pattern[]
while(i<n){
if(pattern[j] == text[i]){
j++; i++;
}
if(j==m){
result.push_back(i-j); //match
j = lps[j-1];
} else if(i < n && pattern[j] != text[i]) {
if(j!= 0){
j = lps[j-1]; //no match, go back
} else{
i++; //thak haar kar ise hi badha diya :)
}
}
}
return result;
}