forked from Masked-coder11/gfg-POTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
09.01.2024.cpp
61 lines (55 loc) · 1.42 KB
/
09.01.2024.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
59
60
61
class Solution
{
public:
vector <int> search(string pat, string txt)
{
//code here.
int n= txt.length();
int m= pat.length();
int len=0;
vector<int>arr(m,0);
int i=1;
while(i<m){
if(pat[i]==pat[len]){
arr[i]=len+1;
len++;
i++;
}
else{
if(len==0){
arr[i]=0;
i++;
}
else{
len = arr[len-1];
}
}
}
// for(auto )
i=0;
int j=0;
vector<int>ans;
while(i<n){
if(pat[j] == txt[i]){
i++;
j++;
}
if(j==m){
ans.push_back(i-j+1);
j=arr[j-1];
}
else if(i<n && pat[j] != txt[i]){
if(j==0){
i++;
}
else{
j=arr[j-1];
}
}
}
if(ans.size()==0){
return {-1};
}
return ans;
}
};