小编asd*_*sdf的帖子

为什么哈希函数是O(1)

为什么查找给定字符串的哈希值只能在恒定时间内运行?

我正在尝试编写一个优化程序来使用字符串哈希来比较两个字符串。

据我所知,字符串的哈希通常由多项式滚动哈希函数定义。网上消息称计算这个哈希值并进行比较的时间复杂度为 O(1)。例如,https://cp-algorithms.com/string/string-hashing.html表示

字符串散列背后的想法如下:我们将每个字符串映射为一个整数,然后比较它们而不是字符串。这样做可以将字符串比较的执行时间减少到 O(1)。

但是,此哈希函数的实际实现(根据https://cp-algorithms.com/string/string-hashing.html)包括循环整个字符串:

long long compute_hash(string const& s) {
const int p = 31;
const int m = 1e9 + 9;
long long hash_value = 0;
long long p_pow = 1;
for (char c : s) {
    hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
    p_pow = (p_pow * p) % m;
}
return hash_value;
}
Run Code Online (Sandbox Code Playgroud)

这难道不能保证比较两个字符串的线性时间复杂度,而不是 O(1) 吗?任何帮助表示赞赏!

c++ string algorithm hash

4
推荐指数
1
解决办法
674
查看次数

标签 统计

algorithm ×1

c++ ×1

hash ×1

string ×1