【发布时间】:2015-07-12 08:58:45
【问题描述】:
我在为我的哈希表实现哈希函数时遇到问题。
我想对我的单词进行哈希处理,使得 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;
}
【问题讨论】:
-
还有免费的失踪...
-
实际上,我根本看不到数组的原因,为什么不简单地添加字母数字(您可以从例如
tolower(word[i]) - 'a' + 1获得)。另外,如果单词中有非字母字符会怎样? -
这实际上让我思考......我的意思是还有其他方法我刚开始学习 C 所以我这样做是为了让事情变得简单
-
你可以像@JoachimPileborg 建议的那样简单,使用
ctype.h中的函数进行字符分类等。 1 数组而不是 2总是更简单。但是在大写/小写转换中,你甚至不需要函数。小写字符代码只是32大于大写,反之亦然。看看ASCII Table and Description