String Hashing - 字符串哈希化

String Hashing - 字符串哈希化

String Hashing (字符串哈希化) 简单理解就是将一个字符串转换为一个整数。一般情况下,hash 值会比原始值更易储存 (更小) 或比较。
不要将任意字符对应到数字 0,一般情况下,将 a - z 对应到数字 1 - 26idx(x) = x - 'a' + 1

Here is an example of calculating the hash of a string s, which contains only lowercase letters. We convert each character of s to an integer. Here we use the conversion a->1, b->2, …, z->26. Converting a->0 is not a good idea, because then the hashes of the strings a, aa, aaa, … all evaluate to 0.
这是一个计算字符串 s 的哈希的示例,该字符串仅包含小写字母。我们将 s 的每个字符转换为整数。这里我们使用转换 a->1, b->2, …, z->26。转换 a->0 不是一个好主意,因为字符串 a, aa, aaa, … 的哈希值都等于 0

//======================================================================================================================
// Yongqiang Cheng
//======================================================================================================================

#include <iostream>

int main() {
    std::string str("abcdefghijklmnopqrstuvwxyz");

    std::cout << "The size of str is " << str.length() << " bytes.\n";

    for (int i = 0; i < str.length(); ++i) {
        int num = (str[i] - 'a' + 1);
        std::cout << num << " ";
    }

    std::cout << std::endl;
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
/home/yongqiang/CLionProjects/hash_table/cmake-build-debug/hash_table
The size of str is 26 bytes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 
Hello, World!

Process finished with exit code 0

References

https://cp-algorithms.com/string/string-hashing.html
http://pages.cs.wisc.edu/~siff/CS367/Notes/hash.html
http://www.cse.yorku.ca/~oz/hash.html
http://cseweb.ucsd.edu/~kube/cls/100/Lectures/lec16/lec16-15.html

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页