原题链接:. - 力扣(LeetCode)
这是一道典型的Hash统计题,唯一难点是如何用C语言实现字符串类型的key的哈希表。正好总结下:
哈希表建立:
typedef struct {
char *key;
int val;
UT_hash_handle hh;
} Hash;
查找键值对:
Hash *hashFind(Hash **obj,const char* key){
Hash *p=NULL;
HASH_FIND_STR(*obj,key,p);
return p;
}
添加元素:
bool hashAdd(Hash **obj,char *key,int val){
if(hashFind(obj,key)){
return false;
}//已有该key值
Hash *p=(Hash*)malloc(sizeof(Hash));
p->key=key;
p->val=val;
HASH_ADD_STR(*obj,key,p);
return true;
}
改变计数value:
bool hashSet(Hash **obj, char *key, int val) {
Hash *p = hashFind(obj, key);
if (!p) {
hashAdd(obj, key, val);//如果没有
} else {
p->val = val;//有的话改变val值
}
return true;
}
获得value值:
int hashGet(Hash **obj, const char *key, int default) {
Hash *p = hashFind(obj, key);
if (p==NULL) {
return default;
}
return p->val;
}
运行代码:
int countWords(char** words1, int words1Size, char** words2, int words2Size) {
Hash *hash1 = NULL, *hash2 = NULL;
int res=0;
for (int i = 0; i < words1Size; i++) {
hashSet(&hash1, words1[i], hashGet(&hash1, words1[i], 0) + 1);//遍历words1,建立hash1
}
for (int i = 0; i < words2Size; i++) {
hashSet(&hash2, words2[i], hashGet(&hash2, words2[i], 0) + 1);//遍历words2,建立hash2
}
for (Hash *p = hash1; p; p = p->hh.next) {
int cnt1 = p->val;
if (cnt1 == 1 && hashGet(&hash2, p->key, 0) == 1) {
++res;
}
}
hashFree(&hash1);
hashFree(&hash2);
return res;
}