1002. Find Common Characters

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. 1 <= A.length <= 100
  2. 1 <= A[i].length <= 100
  3. A[i][j] is a lowercase letter

这道题给了一组由小写字母组成的字符串,让返回所有的字符串中的相同的字符,重复的字符要出现对应的次数。其实这道题的核心就是如何判断字符串的相交部分,跟之前的 Intersection of Two Arrays IIIntersection of Two Arrays 比较类似。核心是要用 HashMap 建立字符和其出现次数之间的映射,这里由于只有小写字母,所以可以使用一个大小为 26 的数组来代替 HashMap。用一个数组 cnt 来记录相同的字母出现的次数,初始化为整型最大值,然后遍历所有的单词,对于每个单词,新建一个大小为 26 的数组t,并统计每个字符出现的次数,然后遍历0到25各个位置,取 cnt 和 t 对应位置上的较小值来更新 cnt 数组,这样得到就是在所有单词里都出现的字母的个数,最后再把这些字符转为字符串加入到结果 res 中即可,参见代码如下:

class Solution {
public:
    vector<string> commonChars(vector<string>& A) {
        vector<string> res;
        vector<int> cnt(26, INT_MAX);
        for (string word : A) {
            vector<int> t(26);
            for (char c : word) ++t[c - 'a'];
            for (int i = 0; i < 26; ++i) {
                cnt[i] = min(cnt[i], t[i]);
            }
        }
        for (int i = 0; i < 26; ++i) {
            for (int j = 0; j < cnt[i]; ++j) {
                res.push_back(string(1, 'a' + i));
            }
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1002

类似题目:

Intersection of Two Arrays II

Intersection of Two Arrays

参考资料:

https://leetcode.com/problems/find-common-characters/

https://leetcode.com/problems/find-common-characters/discuss/247573/C%2B%2B-O(n)-or-O(1)-two-vectors

LeetCode All in One 题目讲解汇总(持续更新中…)


转载请注明来源于 Grandyang 的博客 (grandyang.com),欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 grandyang@qq.com

💰


微信打赏


Venmo 打赏

×

Help us with donation