给你一个字符串数组 words
,请你找出所有在 words
的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
输入:words = ["bella","label","roller"] 输出:["e","l","l"]
示例 2:
输入:words = ["cool","lock","cook"] 输出:["c","o"]
提示:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
由小写英文字母组成
解法:双哈希表,具体解法都写了注释,看下来就行
char ** commonChars(char ** words, int wordsSize, int* returnSize){
//使用哈希表去解题,需要用到两个表
//hash表1,作为主表,用于每次更新
int hash[26] = {0};
//hash_other表用于遍历每个字符串后的哈希表
int hash_other[26] = {0};
//先用第一个字符串给hash赋值
for(int i = 0; i<strlen(words[0]); i++)
{
hash[words[0][i] - 'a']++;
}
//再逐行遍历字符串,每次把结果保存到hash_other中
for(int i = 1; i<wordsSize; i++)
{
//hash_other表的数据只是临时保存,每次向该表中写入数据时,先清空
memset(hash_other, 0, 26*sizeof(int));
for(int j = 0;j<strlen(words[i]); j++)
{
hash_other[words[i][j] - 'a']++;
}
//hash_other的结果是为了更新hash的,取两个表中最小的值记录下来
for(int k = 0; k<26; k++)
{
hash[k] = hash[k] < hash_other[k] ? hash[k]:hash_other[k];
}
}
//统计hash中有几个字符
int count = 0;
for(int i = 0; i<26; i++)
{
count+=hash[i];
}
//把hash中统计到的情况转为字符串输出
char **res = (char**)malloc(sizeof(char*) * count);
*returnSize = 0;
for(int i = 0; i<26; i++)
{
for(int j = 0; j<hash[i]; j++)
{
res[*returnSize] = (char*)malloc(sizeof(char) * 2);
res[*returnSize][0] = (char)('a'+i);
res[*returnSize][1] = '\0';
(*returnSize)++;
}
}
return res;
}