-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
81 lines (62 loc) · 1.7 KB
/
Copy pathKMP.cpp
File metadata and controls
81 lines (62 loc) · 1.7 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
73
74
75
76
77
78
79
80
81
///////////////////////////////////////////////////////////////////////////////
//
// KMP Substring search
//
// Time Complexity
// average: O(n + m)
// worst: O(m * n)
//
///////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#define DEBUG 1
int kmp_search(const std::string& needle, const std::string& haystack)
{
std::vector<int> border(needle.size(), 0);
// process pattern string, construct the border table
for (int i = 1, k = 0; i < needle.size(); ++i)
{
while (k && needle[k] != needle[i])
k = border[k - 1];
if (needle[k] == needle[i])
++k;
border[i] = k;
}
/////////////////////////////////////////////////////////////////////////////
#if DEBUG
std::for_each(border.begin(), border.end(),
[&](const int& item) {
std::cout << item << ' ';
});
std::cout << std::endl;
#endif
/////////////////////////////////////////////////////////////////////////////
for (int i = 0, k = 0; i < haystack.size(); ++i)
{
while (k && needle[k] != haystack[i])
k = border[k - 1];
if (needle[k] == haystack[i]) ++k;
if (k == needle.size()) return i - k + 1;
}
return -1;
}
int main(int argc, char** argv)
{
std::string haystack("test");
std::string needle("aabaabaaaab");
int index{-1};
do {
index = kmp_search(needle, haystack);
if (index > 0)
std::cout << "Found, index: " << index << '\n';
else
std::cout << "Not found\n";
std::cout << "please enter haystack: ";
getline(std::cin, haystack);
std::cout << "please enter needle: ";
getline(std::cin, needle);
} while (true);
return 0;
}