Description
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 <= A.length <= 100
- 1 <= A[i].length <= 100
- A[i][j] is a lowercase letter
分析
题目的意思是:给定一个包含字符串的列表,求出包含的公共字符,如果同一个字符包含了n次,就要输出这个字符n次。这道题是easy题目,我没有做出来,后面发现defaultdict里面可以存放数组,这样把每个字符串的统计结果放到数组里面,然后进行遍历,如果该字符出现在所有的字符串中,就把它放在结果集合里面,注意字符不止出现一次,所以有一个min(v)的操作,找到该字符出现在字符串最少的次数,相乘就得到了满足题意的结果了
代码
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
c = collections.defaultdict(list)
for a in A:
counters=collections.Counter(a)
for key,cnt in counters.items():
c[key].append(cnt)
res=[]
for k,v in c.items():
if(len(v)==len(A)):
res.extend([k]*min(v))
return res