-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkmp.cpp
More file actions
72 lines (69 loc) · 1.29 KB
/
kmp.cpp
File metadata and controls
72 lines (69 loc) · 1.29 KB
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 <string>
#include <vector>
using namespace std;
void kmppreprocess(const string &p, vector<int> &prefix)
{
prefix[0]=0;
int m = p.length();
int i = 1;
int j = 0;
while (i < m)
{
if (p[i] == p[j])
{
j++;
prefix[i] = j;
i++;
}
else
{
if (j != 0)
j = prefix[j - 1];
else
{
prefix[i] = 0;
i++;
}
}
}
}
void KMPsearch(const string &t, const string &p, const vector<int>& prefix)
{
int n= t.length();
int m=p.length();
int i=0,j=0;
while(i<n)
{
if(p[j]==t[i])
{
j++;
i++;
}
if(j==m)
{
cout<<"Found pattern at index: "<<(i-j)<<endl;
j=prefix[j-1];
}
else if(i<n&&p[j]!=t[i])
{
if(j!=0)
{
j=prefix[j-1];
}
else
{
i++;
}
}
}
}
int main()
{
string t = "ABABAABACDABABCABAB";
string p = "ABABCABAB";
vector<int> prefix(p.length());
kmppreprocess(p, prefix);
KMPsearch(t,p,prefix);
return 0;
}