其他分享
首页 > 其他分享> > LeetCode 1002. 查找常用字符

LeetCode 1002. 查找常用字符

作者:互联网

代码随想录链接:

https://gitee.com/programmercarl/leetcode-master/blob/master/problems/1002.查找常用字符.md

思路:

第一步统计每个字符串的字符出现频数并存hash,最后统计每个字符(以第一个串的字符为准即可)出现频数的最小值(为0则表示非共有字符)作为res的字符重复数输出即可

我的代码:

class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        from collections import defaultdict
        dic = [defaultdict(int)]
        for i in range(len(words)):
            dic.append(defaultdict(int))
            for j in range(len(words[i])):
                dic[i][words[i][j]] += 1
        res = []
        minx = float('inf')
        for i in set(words[0]):
            for j in dic:
                if minx > j[i]:
                    minx = j[i]
            for _ in range(minx):
                res.append(i)
            minx = float('inf')
        return res

但还不够简化,随想录提到了collections.Counter,专门统计元素出现频数,且可直接对counter取交集,返回value最小值的键值对(defaultdict不行):

class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        tmp = collections.Counter(words[0])
        l = []
        for i in range(1,len(words)):
            # 使用 & 取交集
            tmp = tmp & collections.Counter(words[i])

        # 剩下的就是每个单词都出现的字符(键),个数(值)
        for j in tmp:
            v = tmp[j]
            while(v):
                l.append(j)
                v -= 1
        return l

标签:tmp,字符,res,1002,minx,查找,words,dic,LeetCode
来源: https://www.cnblogs.com/Linanjing/p/16658916.html