-
Notifications
You must be signed in to change notification settings - Fork 213
/
KMPAlgorithm.cpp
55 lines (52 loc) · 859 Bytes
/
KMPAlgorithm.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
#include<iostream>
#include<string>
using namespace std;
int lps(string s){ //Algo to find the longest properpreffixsuffix example aba=1
int l=s.length();
int k=1,c=0;
for(int i=0;i<l&&k<l;i++){
if(s.substr(0,k)==s.substr(l-i-1,k))
c=k;
++k;
}
//cout<<c;
return c;
}
void KMPAlgorithm(string pat,string txt){
int N=txt.length();
int M=pat.length();
int arrlps[M];
int i=0,j=0;
for(int k=0;k<M;++k)
arrlps[k]=lps(pat.substr(0,k+1));
/*for(int k=0;k<M;++k)
cout<<arrlps[k];*/
while(i<N){
if(pat[i]==txt[j]){
++i;
++j;
}
if(j==M){
cout<<(i-j);
j=arrlps[j-1];
}
else{
if(i<N && pat[i]!=txt[j]){
if(j==0)
++i;
else
j=arrlps[j-1];
}
}
}
}
int main(){
int T;
cin>>T;
while(T--){
string txt,pat;
cin>>txt>>pat;
KMPAlgorithm(pat,txt);
}
return 0;
}