0

我在理解 Java 中通用哈希函数的实现时遇到了一些麻烦。哈希函数(ax + b) mod p应该在 H_1 的基础上实现。这个实现也应该适用于字符串。

我最近在做这个:

public class UniversalHashing {
    // the hash function is a linear function (h(x) = (ax + b) mod p)
    // where a and b are chosen randomly
    // p is a prime number

    private int a;
    private int b;
    private int p;

    public UniversalHashing(int a, int b, int p) {
        this.a = a;
        this.b = b;
        this.p = p;
    }

    public int hash(String string) {
        int hash = 0;
        for (int i = 0; i < string.length(); i++) {
            hash = (hash * a + string.charAt(i)) % p;
        }
        return (hash + b) % p;
    }

    public static void main(String[] args) {
        UniversalHashing h = new UniversalHashing(5, 3, 11);
        System.out.println(h.hash("hello"));
        System.out.println(h.hash("world"));
        System.out.println(h.hash("hello"));
        System.out.println(h.hash("world"));
    }
}

这个实现是正确的,还是我在为 String 实现通用散列函数的路径上完全错误。

谢谢你帮我解决这个问题

4

1 回答 1

0

还是这样的?

import java.math.BigInteger;

public class UniversalHashing {
    private final BigInteger a,b;
    private final long p = 1000000007;

    public UniversalHashing(long m) {
        a = BigInteger.valueOf((long) (Math.random() * p));
        b = BigInteger.valueOf((long) (Math.random() * (p - 1L)));
    }

    public int hashCode(String string) {
        BigInteger hash = BigInteger.valueOf(0);
        for (int i = 0; i < string.length(); i++) {
            hash = hash.add(BigInteger.valueOf(string.charAt(i)).multiply(a.pow(i)));
        }
        return (int) (hash.mod(BigInteger.valueOf(p)).add(b).mod(BigInteger.valueOf(p)).longValue());
    }

    public static void main(String[] args) {
        UniversalHashing uh = new UniversalHashing(1000000007);
        System.out.println(uh.hashCode("abc"));
        System.out.println(uh.hashCode("abcd"));
        System.out.println(uh.hashCode("abcde"));
    }
}
于 2021-11-19T14:57:00.883 回答