【发布时间】:2022-01-10 17:14:48
【问题描述】:
我正在尝试了解 Rabin-Karp 算法的实现。 d 是输入字母表中的字符数,但如果我替换 0 或任何其他值而不是 20,它不会影响任何内容。为什么会这样?
// Rabin-Karp algorithm in C++
#include <string.h>
#include <iostream>
using namespace std;
#define d 20
void rabinKarp(char pattern[], char text[], int q) {
int m = strlen(pattern);
int n = strlen(text);
int i, j;
int p = 0;
int t = 0;
int h = 1;
for (i = 0; i < m - 1; i++)
h = (h * d) % q;
// Calculate hash value for pattern and text
for (i = 0; i < m; i++) {
p = (d * p + pattern[i]) % q;
t = (d * t + text[i]) % q;
}
// Find the match
for (i = 0; i <= n - m; i++) {
if (p == t) {
for (j = 0; j < m; j++) {
if (text[i + j] != pattern[j])
break;
}
if (j == m)
cout << "Pattern is found at position: " << i + 1 << endl;
}
if (i < n - m) {
t = (d * (t - text[i] * h) + text[i + m]) % q;
if (t < 0)
t = (t + q);
}
}
}
int main() {
// char text[] = "ABCCDXAEFGX";
char text[] = "QWERTYUIOPASDFGHJKLXQWERTYUIOPASDFGHJKLX";
char pattern[] = "KLXQW";
int q = 13;
rabinKarp(pattern, text, q);
}
【问题讨论】:
-
当您在调试器中运行此代码时,您看到了什么?这类问题正是调试器非常乐意向您展示的问题,非常有效。您是否尝试在调试器中运行显示的代码?你看到了什么?
-
我不知道我应该看到什么 :)
-
如何编写一个他们不知道应该如何工作的程序或算法?
-
@SamVarshavchik 这是可能的。这只是他遵循的食谱。现在他想知道为什么食谱是这样的。
标签: c++ algorithm rabin-karp