string - 字符串的哈希函数

标签 string algorithm hash

我需要一个字符串(字节)的散列函数

  1. 具有低冲突率(即使对于短字符串也是如此)

  2. 可以快速计算(O(n) 时间是必须的,但我希望它尽可能快)

  3. 给定 hash(string1)hash(string2),计算 hash(append(string1, string2)) 可以在 O(1) 中完成。

到目前为止我能想到的最好的是:(在 Java 伪代码中)

public static int[] HASH_ENTROPY = new int[] {...} // 255 large prime numbers

public int hash()
    int hash = 0;
    for (int i=0; i < this.array.length; i++)
       hash += HASH_ENTROPY[this.array[i] + 128];
    return hash;

有没有更好的算法?这个在 #1 和 #3 上表现不错,但我想知道 如果访问数组中的随机元素太慢。

最佳答案

我建议你使用:

public uint32_t hash()
    uint32_t hash = 0x1f351f35; // 2x Barker code
    for (int i=0; i < this.array.length; i++) {
       char c = this.array[i];
       hash = ((hash << 1) | (hash >> 31)) + (HASH_ENTROPY[(uint8_t)(hash + c)] ^ c);
    }
    return hash;

关于string - 字符串的哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449175/

相关文章:

python - 定义变量类型! PYTHON

algorithm - 实时获取网站排名信息

MySQL:将相关的 BOOL 首选项全部存储在一个整数中作为其二进制值的每一位

php - 在什么情况下,如果我们将排序后的数字作为键添加到哈希表中,我们可以期望哈希是有序的?

无法编译哈希表 ADT - C

java - 如何在 Java 中将大字符串转换为整数?

python - 将字符串添加到字符串

java - 矩阵到字符串输出

algorithm - 双向 A*(A 星)搜索

arrays - 解析数据并适应哈希给出了预期的结果