-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP algo.txt
44 lines (43 loc) · 830 Bytes
/
KMP algo.txt
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
vector<int> constructLps(string s){
int n=s.length();
vector<int> lps(n);
lps[0]=0;
int j=0,i=1;
while(i<n){
if(s[i]==s[j]){
lps[i]=j+1;
i++;
j++;
}
else{
if(j!=0)
j=lps[j-1];
else{
lps[i]=0;
i++;
}
}
}
return lps;
}
int Solution::strStr(const string A, const string B) {
if(B.length()>A.length())
return -1;
vector<int> lps=constructLps(B);
int i=0,j=0,n1=A.length(),n2=B.length();
while(i<n1 and j<n2){
if(A[i]==B[j]){
i++;
j++;
}
else{
if(j!=0)
j=lps[j-1];
else
i++;
}
}
if(j==n2)
return i-j;
return -1;
}