我在为哈希表实现哈希函数时遇到问题.
我想哈希我的话,使得A = 1,B = 2,C = 3,依此类推.字母在单词中的位置是无关紧要的,因为我们会考虑单词的排列.此外,字母的情况也与此问题无关,因此a的值= A = 1的值.
对于字符串,abc = 1 + 2 + 3 = 6,bc = 2 + 3 = 5等.
对于ab = 3和aaa = 3的情况,我已经有办法处理这种情况.现在我只想获得哈希值.
我现在遇到的问题是aaa给了我1,ab给了我2.
以下是我的代码:
int hash(char *word)
{
int h = 1;
int i, j;
char *A;
char *a;
// an array of 26 slots for 26 uppercase letters in the alphabet
A = (char *)malloc(26 * sizeof(char));
// an array of 26 slots for 26 lowercase letters in the alphabet
a = (char *)malloc(26 * sizeof(char));
for (i = 0; i < 26; i++) {
A[i] = (char)(i + 65); // fill the array from A to Z
a[i] = (char)(i + 97); // fill the array from a to z
}
for (i = 0; i < strlen(word); i++) {
//printf("HIT\n");
for (j = 0; j < 26; j++) {
// upper and lower case have the same hash value
if (word[i] == A[j] || word[i] == a[j]) {
h = h + j; // get the hash value of the word
//printf("HIT 2\n");
break;
}
}
}
printf("H: %d\n", h);
return h;
}
Run Code Online (Sandbox Code Playgroud)
我认为改变了
int h = 1;
Run Code Online (Sandbox Code Playgroud)
至
int h = 0;
Run Code Online (Sandbox Code Playgroud)
和
h = h + j;
Run Code Online (Sandbox Code Playgroud)
至
h = h + j + 1;
Run Code Online (Sandbox Code Playgroud)
将解决这个问题.
另一个问题是你忘了释放malloced内存.此外,没有必要malloc在C中投射(和家庭)的结果.
这个
for (i = 0; i < strlen(word); i++) {
Run Code Online (Sandbox Code Playgroud)
将strlen在循环的每次迭代中调用.这会降低程序的性能.使用
int len = strlen(word);
for (i = 0; i < len; i++) {
Run Code Online (Sandbox Code Playgroud)
相反,这比strlen在每次迭代中都没有调用要快得多.最后,sizeof(char)是1.所以你可以省略它.