给定仅有小写字母组成的字符串数组 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]
是小写字母
C++
class Solution {
public:
vector<string> commonChars(vector<string>& A)
{
int n=A.size();
vector<string> res;
vector<vector<int>> tmp(n,vector<int>(26,0));
for(int i=0;i<n;i++)
{
for(int j=0;j<A[i].size();j++)
{
tmp[i][A[i][j]-'a']++;
}
}
for(int k=0;k<26;k++)
{
int count=100;
for(int r=0;r<n;r++)
{
if(tmp[r][k]<count)
{
count=tmp[r][k];
}
}
if(count)
{
for(int i=0;i<count;i++)
{
string aa="";
aa+=('a'+k);
res.push_back(aa);
}
}
}
return res;
}
};
python
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
n=len(A)
res=[]
tmp=[[0 for i in range(26)] for j in range(n)]
for i in range(n):
for j in range(len(A[i])):
tmp[i][ord(A[i][j])-ord('a')]+=1
for k in range(26):
count=100
for r in range(n):
if tmp[r][k]<count:
count=tmp[r][k]
if count:
res+=count*chr(ord('a')+k)
return res