题目描述
给定仅有小写字母组成的字符串数组 A
,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。
示例 1:
输入:["bella","label","roller"] 输出:["e","l","l"]
示例 2:
输入:["cool","lock","cook"] 输出:["c","o"]
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
res = collections.Counter(A[0])
for word in A[1:]:
res &= collections.Counter(word)
return list(res.elements())
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
vector<int> cnt(26, INT_MAX);
vector<string> res;
for(auto s: A)
{
vector<int> cnt1(26, 0);
for(auto c: s) ++cnt1[c - 'a'];
for(int i = 0; i < 26; i++)
cnt[i] = min(cnt[i], cnt1[i]);// ddd
}
for (auto i = 0; i < 26; ++i)
for (auto j = 0; j < cnt[i]; ++j) res.push_back(string(1, i + 'a'));
return res;
}
};