35 int n = text.length(), m = pattern.length();
36 for(s = 0; s <= n - m; s++)
39 if(text.substr(s, m) == pattern)
42 return std::string::npos;
69 static long int poly_hash(
const std::string& input,
int m) {
71 const long int Q = 997;
72 long int hash_val = 0;
73 for(
int i = 0; i < m; i++)
74 hash_val = (hash_val * radix + input[i]) % Q;
78 size_t rabin_karp(
const std::string& text,
const std::string& pattern) {
86 int m = pattern.length();
87 int n = text.length();
88 const long int R = 10;
89 long int pattern_hash = poly_hash(pattern, m);
90 long int text_hash = poly_hash(text, m);
91 long int R_m_minus_1 = std::pow(R, m - 1);
93 if(pattern_hash == text_hash)
94 if(pattern == text.substr(0, m))
96 for(
int s = 1; s <= n - m; s++) {
97 text_hash = (text_hash - R_m_minus_1 * text[s-1]) * R + text[s + m - 1];
98 if(pattern_hash == text_hash)
99 if(pattern == text.substr(s, m))
103 return std::string::npos;
109 size_t horspool(
const std::string& text,
const std::string& pattern) {
111 int skip_table[UCHAR_MAX + 1];
112 int n = text.length(), m = pattern.length();
115 std::fill_n(skip_table, UCHAR_MAX + 1, m);
118 for(
int i = 0; i < m - 1; i++) {
119 skip_table[pattern[i]] = m - i - 1;
125 for(
int shift = 0; shift <= n - m;) {
131 while(i >= 0 && (text[shift + i] == pattern[i]))
138 shift += skip_table[text[shift + m - 1]];
141 return std::string::npos;
151 size_t kmp(
const std::string& text,
const std::string& pattern) {
size_t naive_str_matching(const std::string &text, const std::string &pattern)
Definition: str_matching.h:27
size_t rabin_karp(const std::string &text, const std::string &pattern)
Definition: str_matching.h:78
size_t horspool(const std::string &text, const std::string &pattern)
Definition: str_matching.h:109
size_t kmp(const std::string &text, const std::string &pattern)
Performs substring search in a given string.
Definition: str_matching.h:151