forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMP_Algorithm.cpp
56 lines (52 loc) · 1.29 KB
/
KMP_Algorithm.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
#include<bits/stdc++.h>
using namespace std;
// A string matching algorithm that finds existence of a string as a substring in another string in Linear Time Complexity
int kmp(string haystack, string needle) {
int nsize = needle.size();
int hsize = haystack.size();
if (nsize == 0) return 0;
int *table = new int[nsize];
memset(table, 0, sizeof(int)*nsize);
//building match table
for (int i = 1, j = 0; i < nsize - 1;) {
if (needle[i] != needle[j]) {
if (j > 0) {
j = table[j - 1];
}
else {
i++;
}
}
else {
table[i] = j + 1;
i++;
j++;
}
}
//matching
for (int i = 0, match_pos = 0; i < hsize;) {
if (haystack[i] == needle[match_pos]) {
if (match_pos == nsize - 1) {
return i - (nsize - 1);
}
else {
i++;
match_pos++;
}
}
else {
if (match_pos == 0) {
i++;
}
else {
match_pos = table[match_pos - 1];
}
}
}
delete[]table;
return -1;
}
int main() {
cout << kmp("mississipi", "ssipi") << endl; // 5
return 0;
}