【Lintcode】128. Hash Function

題目地址:

https://www.lintcode.com/problem/hash-function/description

給定一個字符串ss,給定一個數hash_sizehash\_size定義其哈希函數爲h(s)=(s[1]+s[2]33+s[3]332+...)%hash_sizeh(s)=(s[-1]+s[-2]*33+s[-3]*33^2+...)\%hash\_size。要求計算其哈希值。

要用long來做,以防溢出,最後轉成int。代碼如下:

public class Solution {
    /**
     * @param key: A string you should hash
     * @param HASH_SIZE: An integer
     * @return: An integer
     */
    public int hashCode(char[] key, int HASH_SIZE) {
        // write your code here
        long res = 0;
        if (key == null || key.length == 0) {
            return 0;
        }
        
        for (int i = 0; i < key.length; i++) {
            res = res * 33 + key[i];
            res %= HASH_SIZE;
        }
        
        return (int) res;
    }
}

時間複雜度O(n)O(n),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章