-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMP.cpp
57 lines (54 loc) · 1.07 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
//RETURN ALL THE INDICES OF OCCURING STRING NEEDLE
//O(N+M)
vector<int> solve(string &s)
{
int m=s.size();
int i=1, len=0;
vector<int> lpss(m,0);
while(i<m)
{
if(s[i]==s[len])
{
len++;
lpss[i]=len;
i++;
}
else
{
if(len!=0)
len=lpss[len-1];
else
{
lpss[i]=0;
i++;
}
}
}
return lpss;
}
vector<int> strStr(string haystack, string needle) {
int n=haystack.size();
int m=needle.size();
vector<int> lps=solve(needle);
int i=0, j=0;
vector<int> ans;
while(i<n)
{
if(haystack[i]==needle[j])
{
i++;
j++;
}
if(j==m)
{
ans.push_back(i-j);
j=lps[j-1];
}
else if(i<n && haystack[i]!=needle[j])
{
if(j!=0) j=lps[j-1];
else i++;
}
}
return ans;
}