题目描述:
给定仅有小写字母组成的字符串数组 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:
主要思路:
(1)使用unordered_map来统计字符串中字符的出现情形,然后逐个的和后面的字符串中出现的字符求交集;
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
if(A.empty()){
return {};
}
//初始化,统计第一个字符串
unordered_map<char,int> mp;
for(char&ch:A[0]){
++mp[ch];
}
//找后面的字符串中出现的交集
for(int i=0;i<A.size();++i){
unordered_map<char,int>tmp;
for(char&ch:A[i]){
if(mp.count(ch)&&mp[ch]){
++tmp[ch];
--mp[ch];
}
}
mp=tmp;
}
//统计各个字符
vector<string>res;
for(auto& it:mp){
for(int i=0;i<it.second;++i){
string str="";
str+=it.first;
res.push_back(str);
}
}
return res;
}
};