【问题标题】:implementation of rolling hash does not help in String Matching with Rabin Karp滚动哈希的实现在使用 Rabin Karp 进行字符串匹配时没有帮助
【发布时间】:2011-12-11 05:08:54
【问题描述】:

为这个可能重复的问题道歉。

我正在尝试将滚动哈希与 Karp Rabin 一起使用。我查看了滚动哈希的不同实现,我想知道我哪里出错了。尽管文本具有模式,但使用散列的匹配似乎根本没有发生。 附加(一部分)用于计算哈希和搜索的代码。

long hash(char* key, int len) {
int j = 0;
unsigned long long h = 0;
for (j = 0; j < len; j++) {
    h = h * PRIME_BASE + key[j];
    h %= PRIME_MOD;
}
return h;
}



int search(char* pattern, char *txt, int textLength, int patternLength) {

int i, val = 0;

long long txtHash=0;

long power = 1;
for (i = 0; i < patternLength; i++)
    power = (power * PRIME_BASE) % PRIME_MOD;
i=0;
printf(" the value of power is %ld ",power);
for (i = 0; i < textLength; i++) {
    txtHash = txtHash * PRIME_BASE + txt[i];
    txtHash %= PRIME_MOD;
    if (i >= patternLength)
    {
    txtHash -= power * txt[i - patternLength] % PRIME_MOD;

    if (txtHash < 0){
      //negative can be made positive with mod
        txtHash += PRIME_MOD;
    }
    }
    int offset=0;
    if(i>=patternLength){
    offset=i-patternLength+1;
    }
    else{
        offset=0;
    }

    if (patHash == txtHash) {
        if (check(pattern, txt, offset, patternLength)) {
            val++;
        }
    }

}
if (val > 0) {
    return val;
}
// no match
return 0;
}


bool check(char* pattern, char* txt, int k, int M) {
int j = 0;

for (j = 0; j < M; j++) {
    if (pattern[j] != txt[k + j]) {
        return false;
    }
}
return true;
}

我遇到了缓冲区溢出的问题,我已经处理过了,但模式和文本哈希似乎与蛋白质序列文本字符串(1000 个字符)和 17 个字符模式不匹配 有什么想法我可能会出错吗?

谢谢, 八卦

【问题讨论】:

  • 我使用的不是滚动散列,而是通过重复调用散列函数来计算文本的散列,这似乎是有效的,但当然性能不如蛮力算法

标签: c hash rabin-karp


【解决方案1】:

我在这个问题上花了一些时间,发现因为我已经将 long long txtHash 的值初始化为某个默认值,所以我遇到了哈希不匹配的情况。用修复更新上面的代码

【讨论】:

    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2011-05-20
    • 2017-07-27
    • 1970-01-01
    • 2011-01-19
    • 2021-08-03
    相关资源
    最近更新 更多