[leetcode] 1002. Find Common Characters

网友投稿 875 2022-08-22

[leetcode] 1002. Find Common Characters

[leetcode] 1002. Find Common Characters

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 <= 1001 <= A[i].length <= 100A[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

参考文献

​​[LeetCode] Python easy to understand solution using Counter​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Android手把手教你实现搜索框(androidstudio搜索框)
下一篇:[leetcode] 1007. Minimum Domino Rotations For Equal Row
相关文章

 发表评论

暂时没有评论,来抢沙发吧~