给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。

    你可以按任意顺序返回答案。

    示例 1:

    输入:[“bella”,”label”,”roller”]

    输出:[“e”,”l”,”l”]

    示例 2:

    输入:[“cool”,”lock”,”cook”]

    输出:[“c”,”o”]


    提示:

    1 <= A.length <= 100

    1 <= A[i].length <= 100

    A[i][j] 是小写字母

    空间复杂度可以优化,有兴趣自己尝试。

    1. class Solution {
    2. public:
    3. vector<string> commonChars(vector<string>& A)
    4. {
    5. // 每一个字符串中26个字母出现次数
    6. int n = A.size();
    7. vector<vector<int>> tmp(n, vector<int>(26, 0));
    8. for(int i=0; i<n; ++i)
    9. {
    10. for(auto ch : A[i])
    11. {
    12. tmp[i][ch - 'a']++;
    13. }
    14. }
    15. // 得到每一个字母在每一个字符中出现最小次数
    16. vector<int> cnts(26, INT_MAX);
    17. for(int i=0; i<26; ++i)
    18. {
    19. for(int j=0; j<n; ++j)
    20. cnts[i] = min(cnts[i], tmp[j][i]);
    21. }
    22. // 在所有字符串中出现字符次数
    23. vector<string> ans;
    24. for(int i=0; i<26; ++i)
    25. {
    26. int cnt = cnts[i];
    27. while(cnt--)
    28. ans.emplace_back(string(1, i + 'a'));
    29. }
    30. return ans;
    31. }
    32. };

    欢迎交流,批评指正!