Leetcode1002: 查找常用字符

目录

一、题目

二、示例

三、思路

四、代码


一、题目

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。

你可以按任意顺序返回答案。

二、示例

示例 1:

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

示例 2:

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

提示:

  • 1 <= A.length <= 100
  • 1 <= A[i].length <= 100
  • A[i][j] 是小写字母

三、思路

两个for循环:

第一个for循环用来遍历每一个单词;第二个for循环遍历每个单词的字母

两个数组:

数组tmp记录每一个单词中的字母出现的个数,数组mintmp记录单词出现的最小次数

最后将其输入即可。

四、代码

class Solution:
    def commonChars(self, A):
        """
        :type A: List[str]
        :rtype: List[str]
        """
        mintmp = [float("inf")] * 26
        ans = []
        for word in A:
            tmp = [0 for _ in range(26)]
            for i in word:
                tmp[ord(i) - ord("a")] += 1
            for j in range(26):
                mintmp[j] = min(mintmp[j], tmp[j])
        # print(mintmp)
        for i in range(26):
            ans.extend([chr(i + ord("a"))] * mintmp[i])
        return ans

if __name__ == '__main__':
    test = ["bella","label","roller"]
    s = Solution()
    ans = s.commonChars(test)
    print(ans)

猜你喜欢

转载自blog.csdn.net/weixin_45666660/article/details/109092405