1002. 查找共用字符(C语言,哈希表解法)

该文章介绍了一个使用双哈希表的算法来找出字符串数组中所有字符串共有的字符,包括重复字符。首先,初始化两个哈希表,用第一个字符串填充主哈希表,然后遍历其余字符串,更新主哈希表以保存每个字符串出现的最小次数。最后,从哈希表中统计并转换成字符数组返回结果。
摘要由CSDN通过智能技术生成

给你一个字符串数组 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值