27 for (
int i = 0; i < n; ++i) {
28 result += (int64_t)(s[i] * (int64_t)pow(
PRIME, i));
43 int64_t old_hash,
int patLength) {
44 int64_t new_hash = old_hash - s[old_index];
46 new_hash += (int64_t)(s[new_index] * (int64_t)pow(
PRIME, patLength - 1));
61 int start1,
int end1,
int start2,
int end2) {
62 if (end1 - start1 != end2 - start2) {
65 while (start1 <= end1 && start2 <= end2) {
66 if (str1[start1] != str2[start2]) {
83int rabin_karp(
const std::string& str,
const std::string& pat) {
86 for (
int i = 0; i <= str.size() - pat.size(); ++i) {
87 if (pat_hash == str_hash &&
92 if (i < str.size() - pat.size()) {
106 assert(rabin_karp(
"helloWorld",
"world") == -1);
107 assert(rabin_karp(
"helloWorld",
"World") == 5);
108 assert(rabin_karp(
"this_is_c++",
"c++") == 8);
109 assert(rabin_karp(
"happy_coding",
"happy") == 0);
String search algorithms.
int rabin_karp(const std::string &str, const std::string &pat)
int64_t create_hash(const std::string &s, int n)
bool check_if_equal(const std::string &str1, const std::string &str2, int start1, int end1, int start2, int end2)
int64_t recalculate_hash(const std::string &s, int old_index, int new_index, int64_t old_hash, int patLength)
#define PRIME
Prime modulus for hash functions.