-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch Pattern (KMP-Algorithm).cpp
More file actions
56 lines (45 loc) · 1.39 KB
/
Search Pattern (KMP-Algorithm).cpp
File metadata and controls
56 lines (45 loc) · 1.39 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
class Solution
{
public:
vector <int> search(string pat, string txt)
{
//code hee.
vector<int> res;
int n=pat.length();
int lps[n]={0};
int start=0;
for(int i =1;i<pat.length();i++){
if(pat[start]==pat[i]){
lps[i]=start+1;
start++;
}
else{
start=0;
lps[i]=0;
}
}
start=0;
int pat_len=pat.length();
int i=0;
while(i<txt.length()){
if(start<pat_len && txt[i]==pat[start]){
start++;
if(start==pat_len){
res.push_back(i-pat_len+2);
start=lps[start-1];
}
i++;
}
else{
// cout<<"here";
if(start>0)
start=lps[start-1];
else{
i++;
}
// cout<<start<<endl;
}
}
return res;
}
};