-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP-algo.cpp
49 lines (45 loc) · 890 Bytes
/
KMP-algo.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
#include <bits/stdc++.h>
using namespace std;
vector<int> prefix_function(string s){
int n=s.size(), len=0,i=1;
vector<int> pi(n,0);
while(i<n){
if(s[len]==s[i]){
pi[i]=len+1;
++i;
++len;
}else{
if(len!=0){
len=pi[len-1];
}else{
pi[i]=0;
++i;
}
}
}
return pi;
}
int main(){
string t = "abcabcd";
string s = "ca";
int pos=-1;
vector<int> pi = prefix_function(s);
int i(0), j(0);
while(i<t.size()){
if(t[i]==s[j]){
++i;
++j;
}else{
if(j!=0){
j=pi[j-1];
}else{
i++;
}
}
if(j==s.size()){
pos=i-s.size();
break;
}
}
cout<<pos<<endl;
}