-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathkmp_algo.cpp
More file actions
77 lines (68 loc) · 871 Bytes
/
kmp_algo.cpp
File metadata and controls
77 lines (68 loc) · 871 Bytes
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
73
74
75
76
77
#include <bits/stdc++.h>
using namespace std;
void compute_lps(int *lps,string pat)
{
int prev =0;
int i=1;
lps[0] = 0;
while(i<pat.size())
{
if(pat[prev]==pat[i])
{
prev++;
lps[i] = prev;
i++;
}
else
{
if(prev == 0)
{
lps[i]=0;
i++;
}
else
{
prev = lps[prev-1];
}
}
}
}
void KMP_search(string pat,string s)
{
int lps[pat.size()];
compute_lps(lps,pat);
int i=0;
int j=0;
while(i<s.size())
{
cout<<"i: "<<i<<" j: "<<j<<endl;
if(pat[j]==s[i])
{
i++;
j++;
}
else
{
if(j==0)
i++;
else
j = lps[j-1];
}
if(j==pat.size())
{
cout<<"Matched at index : "<<i<<endl;
j= lps[j-1];
}
}
}
int main()
{
string a;
a = "ABABDABACDABABCABAB";
string pat;
pat = "ABABCABAB";
int A[pat.size()];
compute_lps(A,pat);
cout<<A[pat.size()-1]<<endl;
KMP_search(pat,a);
}