我正在为Rabin-Karp算法寻找一个有效的散列函数。这是我的实际代码(C编程语言)。
static bool f2(char const *const s1, size_t const n1,
char const *const s2, size_t const n2)
{
uintmax_t hsub = hash(s2, n2);
uintmax_t hs = hash(s1, n1);
size_t nmax = n2 - n1;
for (size_t i = 0; i < nmax; ++i) {
if (hs == hsub) {
if (strncmp(&s1[i], s2, i + n2 - 1) == 0)
return true;
}
hs = hash(&s1[i + 1], i + n2);
}
return false;
}我考虑了一些Rabin-Karp C实现,但所有代码之间都存在差异。所以我的问题是: Rabin-Karp散列函数应该具有哪些特征?
发布于 2012-07-19 01:55:00
伯恩斯坦散列是一种性能非常好的散列。它甚至超过了许多流行的散列算法。
unsigned bernstein_hash ( void *key, int len )
{
unsigned char *p = key;
unsigned h = 0;
int i;
for ( i = 0; i < len; i++ )
h = 33 * h + p[i];
return h;
}当然,您也可以尝试其他散列算法,如下所述:Hash function on NIST
注意:从来没有人解释过为什么33的性能比任何其他“更符合逻辑”的常量要好得多。
为了引起您的兴趣:下面是不同散列算法的一个很好的比较:strchr comparison of hash algorithms
发布于 2020-10-09 22:46:04
对于小字母表的问题,例如核酸序列搜索(例如alphabet = {A, T, C, G, U}),nt-Hash可能是一个很好的散列函数。它使用二进制运算,更快,滚动哈希更新,并给出均匀分布的哈希值。
https://stackoverflow.com/questions/11546791
复制相似问题