-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathkmp.cpp
74 lines (68 loc) · 1.32 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
65
66
67
68
69
70
71
72
#include<iostream>
#include<vector>
#include<cstdio>
#include<algorithm>
#include<map>
#include<cstring>
#include<set>
using namespace std;
#define uii long long int
#define M(a,b) (a>b ? a : b)
#define m(a,b) (a>b ? b : a)
#define it(a) ::iterator a
#define slld(a) uii a;scanf("%lld",&a)
#define ss(a) scanf("%s",a)
#define plld(a) printf("%lld",a)
#define MAX 10000
#define MOD 1000000007
#define powOf2(a) !(a&a-1)
#define mod(a) (a>0 ? a : (-1*a))
#define tc(a) uii a; for(scanf("%lld",&a);a--;)
#define swap(a,b) a = a^b; b = a^b;a = a^b;
void calculatePatternArray(uii *A,string p){
uii plen = p.size();
uii j = 0;
for(uii i = 1;i<plen;i++){
if(p[i] == p[j]) A[i] = ++j;
else if(j == 0) A[i] = 0;
else{
j = A[j-1];
i--;
}
}
for(uii i = 0;i<plen;i++) cout<<A[i]<<" ";
cout<<endl;
return;
}
void kmp(string p, string text){
uii tlen = text.size();
uii plen = p.size();
uii A[plen] = {0};
calculatePatternArray(A,p);
uii tp = 0,pp = 0;
while(tp<tlen){
if(p[pp] == text[tp]){
//cout<<"tp : "<<tp<<endl;
tp++;
pp++;
}
else if(pp == 0){
tp++;
}
else{
pp = A[pp-1];
}
if(pp == plen){
cout<<"Pattern found at : "<<tp-plen<<endl;
pp = A[pp-1];
}
}
return;
}
int main(){
string pattern;
string text = "Load text before hand";
cin>>pattern;
kmp(pattern,text);
return 0;
}