【每日一题20220729】查找共用字符

:mage:‍给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按任意顺序返回答案。

示例 1:

输入:words = ["bella","label","roller"]
输出:["e","l","l"]

示例 2:

输入:words = ["cool","lock","cook"]
输出:["c","o"]

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] 由小写英文字母组成

任务

编写一个函数, 完成上述操作

class Solution:
    def commonChars(self, words):
    # your code here

题目难度:简单
题目来源:1002. 查找共用字符 - 力扣(LeetCode)

    def commonChars(self, words: List[str]) -> List[str]:
        dict1 = dict.fromkeys(string.ascii_lowercase, 101)
        for i in words:
            for  key in dict1:
                if i.count(key)<dict1[key]:
                    dict1[key] = i.count(key)
        result=[]
        for key,value in dict1.items():
            if  value>0:
                result.extend([key]*value)
        return result

秒啊

class Solution:
    def commonChars(self, words):
        # your code here
        res = []
        keys = set(words[0])
        for key in keys:
            minnum = min(i.count(key) for i in words)
            res += [key] * minnum
        return res
关闭