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

参考文献

[LeetCode] Python easy to understand solution using Counter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值