LeetCode C++ 1002. Find Common Characters【Hash Table】简单

Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.

You may return the answer in any order.

Example 1:

Input: ["bella","label","roller"]
Output: ["e","l","l"]

Example 2:

Input: ["cool","lock","cook"]
Output: ["c","o"]

Note:

  • 1 <= A.length <= 100
  • 1 <= A[i].length <= 100
  • A[i][j] is a lowercase letter

题意:求出多个字符串的字符交集,允许重复字符。

思路:以第一个例子为例,我们知道第一个字符串 bella 的字符数量列表为:

b 1
e 1
l 2
a 1

第二个字符串 label 的字符数量列表为:

l 2
a 1
b 1
e 1

第三个字符串 roller 的字符数量列表为:

r 2
o 1
l 2
e 1

这三个求交集后的结果为:

e 1
l 2

我们可以用哈希表+计数索引来表示字符-数量之间的关系,考虑到效率直接用数组即可。这个题目基本是 350. Intersection of Two Arrays II 的升级版,只是不是两个数组而是多个字符数组。

代码中用到了一个不太常用的 string 构造函数:

class Solution {
public:
    vector<string> commonChars(vector<string>& A) {
        vector<string> ans;
        int cnt[26] = {0};
        for (char c : A[0]) ++cnt[c - 'a'];
        for (int i = 1; i < A.size(); ++i) {
            int tmp[26] = {0};
            for (char c : A[i]) ++tmp[c - 'a'];
            for (int j = 0; j < 26; ++j)
                cnt[j] = min(cnt[j], tmp[j]);  //每两个字符串之间求出字符交集数量
        }
        for (int i = 0; i < 26; ++i) {
            if (cnt[i]) {
                for (int j = 0; j < cnt[i]; ++j) {
                    ans.push_back(string(1, 'a' + i));
                }
            }
        }
        return ans;
    }
};

效率:

执行用时:16 ms, 在所有 C++ 提交中击败了61.26% 的用户
内存消耗:9.1 MB, 在所有 C++ 提交中击败了100.00% 的用户
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值