我们怎样才能写出一个给定素数的多项式散列函数呢



那么,对于给定的素数31,我如何为字符串参数编写哈希函数?

这是我的尝试。

private int hash(String key){
int c = 31;
int hash = 0;

for (int i = 0; i < key.length(); i++ ) {
int ascii = key.charAt(i);
hash += c * hash + ascii; 
}
return (hash % sizetable);} // sizetable is an integer which is declared outside. You can see it as a table.length().

所以,既然我不能在工作中运行任何其他功能,而且我需要确定这里的流程,我需要你的回答和帮助!非常感谢。

您的实现看起来与标准String.hashCode()实现非常相似,甚至还使用了31作为素数,所以它应该足够好。

我只是不将31分配给变量,而是声明一个private static final字段或直接将其用作幻数——通常情况下不好,但在这种情况下可能可以。

此外,如果你已经知道单元测试的概念,你应该添加一些测试,以证明你的方法为不同的字符串提供了不同的哈希。并且聪明地挑选样本,所以它们是不同的(对于家庭作业的情况;(

最新更新