-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmp.cpp
64 lines (56 loc) · 1.19 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
58
59
60
61
62
63
64
#include<bits/stdc++.h>
using namespace std;
vector<int>makeprefixarray(string s){
int n = s.size();
int prevLPS=0;
vector<int>prefix(n,0);
int curr=1;
while(curr<n){
if(s[curr] == s[prevLPS]){
prefix[curr] = prevLPS+1;
prevLPS+=1;
curr+=1;
}
else{
if(prevLPS == 0){
prefix[curr]=0;
curr+=1;
}
else{
prevLPS = prefix[prevLPS-1];
}
}
}
return prefix;
}
int kmp(string t,string p){
vector<int>prefix=makeprefixarray(p);
int i(0),j(0);
int pos=-1;
while(i<t.size()){
if(t[i] == p[j]){
i+=1;
j+=1;
}
else{
if(j==0){
i+=1;
}
else{
j=prefix[j-1];
}
}
if(j == p.size()){
pos = i-p.size();
break;//for first occurance
}//change as per your need
}
return pos;
}
int main(){
string t="aabaaabaaac";
string p="aabaaac";
// vector<int>prefix=makeprefixarray(p);
cout<<kmp(t,p)<<endl;
return 0;
}