Hash function for a string

后端 未结 5 2068
青春惊慌失措
青春惊慌失措 2020-12-01 06:40

We are currently dealing with hash function in my class. Our instructor asked us to a hash function on the internet to compare to the two we have used in our code.

T

5条回答
  •  日久生厌
    2020-12-01 07:08

    Java's String implements hashCode like this:

    public int hashCode()
    
    Returns a hash code for this string. The hash code for a String object is computed as
    
         s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
    
    using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) 
    

    So something like this:

    int HashTable::hash (string word) {
        int result = 0;
        for(size_t i = 0; i < word.length(); ++i) {
            result += word[i] * pow(31, i);
        }
        return result;
    }
    

提交回复
热议问题