示例 1:
输入:words1 = [“leetcode”,“is”,“amazing”,“as”,“is”], words2 = [“amazing”,“leetcode”,“is”]
输出:2
解释:
- “leetcode” 在两个数组中都恰好出现一次,计入答案。
- “amazing” 在两个数组中都恰好出现一次,计入答案。
- “is” 在两个数组中都出现过,但在 words1 中出现了 2 次,不计入答案。
- “as” 在 words1 中出现了一次,但是在 words2 中没有出现过,不计入答案。
所以,有 2 个字符串在两个数组中都恰好出现了一次。
示例 2:
输入:words1 = [“b”,“bb”,“bbb”], words2 = [“a”,“aa”,“aaa”]
输出:0
解释:没有字符串在两个数组中都恰好出现一次。
示例 3:
输入:words1 = [“a”,“ab”], words2 = [“a”,“a”,“a”,“ab”]
输出:1
解释:唯一在两个数组中都出现一次的字符串是 “ab” 。
解题代码如下所示:
#define size 2000
struct hash{
char s[40];
int words1num;
int words2num;
struct hash *next;
};
struct hash* create_hash(){
struct hash* hash_table=(struct hash*)malloc(sizeof(struct hash)*size);
int i;
for(i=0;i
(hash_table+i)->next=NULL;
}
return hash_table;
}
void add_hash(int key, struct hash* hash_table,char *s,int r){
struct hash *p=hash_table+key;
// printf("key %d ",key);
hash_table=hash_table+key;
p=p->next;
while(p){
// printf("%s %s",p->s,s);
if(strcmp(p->s,s)==0){
if(r==1){
p->words1num++;
}
else{
p->words2num++;
}
break;
}
p=p->next;
}
if(p==NULL){
struct hash* t=(struct hash*)malloc(sizeof(struct hash));
strcpy(t->s,s);
if(r==1){
t->words1num=1;
t->words2num=0;
}
else{
t->words2num=1;
t->words1num=0;
}
t->next=hash_table->next;
hash_table->next=t;
}
}
int print_hash(struct hash* hash_table){
int i=0;
struct hash *p;
int sum=0;
for(i=0;i
p=(hash_table+i)->next;
while(p){
// printf("index %d %d %d ",i,p->words1num,p->words2num);
if(p->words1num==1&&p->words2num==1){
sum++;
}
p=p->next;
}
}
return sum;
}
int countWords(char ** words1, int words1Size, char ** words2, int words2Size){
struct hash *h;
h=create_hash();
int i;
for(i=0;i
int j=0;
int num=0;
while(words1[i][j]!=' '&&j<=10){
j++;
num=num+words1[i][j];
}
// printf("word1 %d ",num);
add_hash(num,h,words1[i],1);
}
for(i=0;i
int j=0;
int num=0;
while(words2[i][j]!=' '&&j<=10){
j++;
num=num+words2[i][j];
}
// printf("word2 %d ",num);
add_hash(num,h,words2[i],2);
}
int sum=print_hash(h);
return sum;
}



