AlgoPlus v0.1.0
Loading...
Searching...
No Matches
kmp.h
1#ifndef KMP_H
2#define KMP_H
3
4#ifdef __cplusplus
5#include <iostream>
6#include <string>
7#include <vector>
8#endif
9
10namespace helper_array {
11std::vector<int> get_array(std::string& pattern) {
12 std::vector<int> failure(pattern.size() + 1);
13 failure[0] = -1;
14 for (int i = 0, j = -1; i < pattern.size(); i++) {
15 while (j != -1 && pattern[j] != pattern[i]) {
16 j = failure[j];
17 }
18 failure[i + 1] = ++j;
19 }
20 return failure;
21}
22}; // namespace helper_array
23
32bool kmp(std::string pattern, std::string text) {
33 std::vector<int> failure = helper_array::get_array(pattern);
34 for (int j = 0, k = 0; j < text.size(); j++) {
35 while (k != -1 && pattern[k] != text[j]) {
36 k = failure[k];
37 }
38 if (++k == pattern.size())
39 return true;
40 }
41 return false;
42}
43
44#endif