Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 1002. Find Common Characters #1002

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 1002. Find Common Characters #1002

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

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 同步地址:

#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 题目讲解汇总(持续更新中...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant