-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp_algorithm.cpp
More file actions
69 lines (60 loc) · 1.35 KB
/
Copy pathkmp_algorithm.cpp
File metadata and controls
69 lines (60 loc) · 1.35 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
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
vector<int> prefix_function(string s)
{
int n = (int)s.length();
vector<int> pi(n);
for (int i = 1; i < n; i++)
{
int j = pi[i-1];
while (j > 0 && s[i] != s[j]) //when we have a mismatch
{
j = pi[j - 1];
}
if (s[i] == s[j]) //when we have a match
{
j++;
}
pi[i] = j;
//cout << pi[i];
}
//cout << endl;
return pi;
}
void kmpAlg(string text, string pattern )
{
//prepare Pi table
vector<int> piTable = prefix_function(pattern);
int i=0, j = 0;
while ( i < text.length() )
{
if(pattern[j] == text[i]) // if theres a match, keep going
{
j++;
i++;
}
if ( j == pattern.length() )
{
printf("Found pattern at index %d \n", i - j);
j = piTable[j - 1];
}
else if (i < text.length() && pattern[j] != text[i])
{
if (j != 0)
j = piTable[j - 1];
else
i = i + 1;
}
}
}
int main(int argc, char *argv[])
{
string text = "ABABDABACDABABCABAB";
string pattern = "ABABCABAB";
kmpAlg(text, pattern);
//prefix_function(pattern);
return 0;
}