在 java 中使用 Horner 的方法仅散列字母

Hash only LETTERS using Horner's method in java

我了解 Horner 散列法的工作原理,但我在散列可能包含非字母字符的字符串时遇到问题,我只想散列字母字符。我想忽略非字母字符并只散列字母字符 这是我为此所做的代码,但并不完全有效

private int hash(String key){
int constant = 27;

int lastHashValue = key.charAt(0); //convert the first char to ascii first 
                                   //because for each character we multiply the constant by the
                                   // hash code by the constant. 

 for(int i = 1; i < key.length(); i++){

   if( Character.isLetter(key.charAt(i)) ){ //checks if it is a letter 
      lastHashValue  = (key.charAt(i) + (constant * lastHashValue) ) % array.length;
    }
 }

 return lastHashValue;
}

这是我遇到的问题:如果第一个字符是非字母字符怎么办。我该如何忽略它? (知道我们需要得到第一个字符哈希码才能移动到下一个)。

您可以将 lastHashValue 初始化为 0 并从索引 0 开始循环。

 int lastHashValue = 0; 

 for(int i = 0; i < key.length(); i++){

   if( Character.isLetter(key.charAt(i)) ){ //checks if it is a letter 
      lastHashValue  = (key.charAt(i) + (constant * lastHashValue) ) % array.length;
    }
 }