TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
knuth_morris_pratt.cpp
Go to the documentation of this file.
1
15
16
#include <cassert>
17
#include <iostream>
18
#include <string>
19
#include <vector>
20
25
namespace
string_search
{
32
std::vector<size_t>
getFailureArray
(
const
std::string &pattern) {
33
size_t
pattern_length = pattern.size();
34
std::vector<size_t> failure(pattern_length + 1);
35
failure[0] = std::string::npos;
36
size_t
j = std::string::npos;
37
for
(
int
i = 0; i < pattern_length; i++) {
38
while
(j != std::string::npos && pattern[j] != pattern[i]) {
39
j = failure[j];
40
}
41
failure[i + 1] = ++j;
42
}
43
return
failure;
44
}
45
53
size_t
kmp
(
const
std::string &pattern,
const
std::string &text) {
54
if
(pattern.empty()) {
55
return
0;
56
}
57
std::vector<size_t> failure =
getFailureArray
(pattern);
58
size_t
text_length = text.size();
59
size_t
pattern_length = pattern.size();
60
size_t
k = 0;
61
for
(
size_t
j = 0; j < text_length; j++) {
62
while
(k != std::string::npos && pattern[k] != text[j]) {
63
k = failure[k];
64
}
65
if
(++k == pattern_length) {
66
return
j - k + 1;
67
}
68
}
69
return
std::string::npos;
70
}
71
}
// namespace string_search
72
73
using
string_search::kmp
;
74
79
static
void
tests
() {
80
assert(
kmp
(
"abc1abc12l"
,
"alskfjaldsabc1abc1abc12k2"
) == std::string::npos);
81
assert(
kmp
(
"bca"
,
"abcabc"
) == 1);
82
assert(
kmp
(
"World"
,
"helloWorld"
) == 5);
83
assert(
kmp
(
"c++"
,
"his_is_c++"
) == 7);
84
assert(
kmp
(
"happy"
,
"happy_coding"
) == 0);
85
assert(
kmp
(
""
,
"pattern is empty"
) == 0);
86
87
// this lets the user know that the tests have passed
88
std::cout <<
"All KMP algorithm tests have successfully passed!\n"
;
89
}
90
91
/*
92
* @brief Main function
93
* @returns 0 on exit
94
*/
95
int
main
() {
96
tests
();
97
return
0;
98
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
kmp
size_t kmp(const std::string &pattern, const std::string &text)
KMP algorithm to find a pattern in a text.
Definition
knuth_morris_pratt.cpp:53
string_search
String search algorithms.
Definition
brute_force_string_searching.cpp:13
string_search::kmp
size_t kmp(const std::string &pattern, const std::string &text)
KMP algorithm to find a pattern in a text.
Definition
knuth_morris_pratt.cpp:53
string_search::getFailureArray
std::vector< size_t > getFailureArray(const std::string &pattern)
Generate the partial match table aka failure function for a pattern to search.
Definition
knuth_morris_pratt.cpp:32
tests
Testcases to check Union of Two Arrays.
strings
knuth_morris_pratt.cpp
Generated by
1.18.0