forked from abhaysinghr516/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP algorithm
More file actions
54 lines (48 loc) · 1.17 KB
/
KMP algorithm
File metadata and controls
54 lines (48 loc) · 1.17 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
// Pattern Matching Algorithm by using KMP Algorithm
class Solution {
public:
vector<int> fillLPS(string str){
int n = str.size();
vector<int>lps(n,0);
int len =0, i = 1;
lps[0]=0;
while(i<n){
if(str[len] == str[i]){
len++;
lps[i] = len;
i++;
}else{
if(len == 0){
lps[i]=0;
i++;
}else{
len = lps[len-1];
}
}
}
return lps;
}
int strStr(string haystack, string needle) {
int n = haystack.size();
int m = needle.size();
vector<int>lps = fillLPS(needle);
int i=0, j=0;
while(i<n){
if(haystack[i] == needle[j]){
i++;
j++;
if(j==m){
return i-j;
}
}
else if(i<n && haystack[i] != needle[j]){
if(j==0)
i++;
else{
j = lps[j-1];
}
}
}
return -1;
}
};