往一个字符串数组当中插入5个不同的字符串,然后输入一个字符串,使用下列哈希算法判断该字符串是否出现在数组当中,如果出现,它的下标是多少?
用哈希查找的好处:不用遍历数组,只需要通过哈希函数映射到对应的位置,检查是否有该字符串即可,查找的时间复杂度近似0(1)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MAXKEY 10000
int hash(char *key) {//哈希函数:输入字符串的地址返回字符串对应的哈希值
int h = 0 , g;
while (*key) {
h = (h << 4) + *key++;
g = h & 0xf0000000;
if (g)
h ^= g >> 24;
h &= ~g;
}
return h % MAXKEY;
}
typedef struct info//哈希数组的元素指向info
{
int index;//字符串在数组中的下标
char *address;//存字符串的地址
}Info_t,*pInfo_t;
int main()
{
//指针数组:存字符串的地址,字符串字面值保存在.rodata区
char *name[]={"he","nihao","dajie","baobei","lady"};
//int hashTable[]没有下面这种易扩展,如果想知道字符串所在下标与字符串的地址,那么int hashTable[]就无法满足
pInfo_t hashTable[MAXKEY]={NULL};
for(int i=0;i<sizeof(name)/sizeof(char*);i++)
{//假设不会发生冲突
pInfo_t p=(pInfo_t)calloc(1,sizeof(Info_t));
p->index=i;
p->address=name[i];
hashTable[hash(name[i])]=p;
}
char s[100];
while(rewind(stdin),scanf("%s",s)!=EOF)
{
pInfo_t p=hashTable[hash(s)];
if(p==NULL)
{
printf("NO\n");
}
else
{
printf("%s\n",p->address);
printf("YES,下标是%d\n",p->index);
}
}
return 0;
}