-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathImplementstrStr-KMP.cpp
More file actions
59 lines (50 loc) · 1.33 KB
/
ImplementstrStr-KMP.cpp
File metadata and controls
59 lines (50 loc) · 1.33 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
class Solution {
public:
void computeLPSArray(string pat, int m, int* lps) {
int len = 0;
lps[0] = 0;
int i = 1;
while(i < m) {
if(pat[i] == pat[len]) {
//If Equal we store len at curr index
lps[i++] = ++len;
}
else {
//If not equal
if(len != 0)
len = lps[len - 1];
else {
//If len == 0
lps[i] = 0;
i++;
}
}
}
}
int strStr(string txt, string pat) {
// KMP algorithm
int n = txt.length();
int m = pat.length();
if(!m)
return 0;
int lps[m];
computeLPSArray(pat, m, lps);
int i = 0;
int j = 0;
while(i < n) {
if(pat[j] == txt[i])
i++, j++;
if(j == m)
return i - j;
else if(i < n && pat[j] != txt[i]) {
//move j
if(j != 0)
j = lps[j - 1];
// inc i to find match with j if j == 0
else
i++;
}
}
return -1;
}
};