力扣刷题2023-04-19-1——题目:916. 单词子集

题目:

给你两个字符串数组 words1 和 words2

现在,如果 b 中的每个字母都出现在 a 中,包括重复出现的字母,那么称字符串 b 是字符串 a 的 子集 。

  • 例如,"wrr" 是 "warrior" 的子集,但不是 "world" 的子集。

如果对 words2 中的每一个单词 bb 都是 a 的子集,那么我们称 words1 中的单词 a 是 通用单词 

以数组形式返回 words1 中所有的通用单词。你可以按 任意顺序 返回答案。

示例 1:

输入:words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]
输出:["facebook","google","leetcode"]

示例 2:

输入:words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"]
输出:["apple","google","leetcode"]

示例 3:

输入:words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","oo"]
输出:["facebook","google"]

示例 4:

输入:words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["lo","eo"]
输出:["google","leetcode"]

示例 5:

输入:words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["ec","oc","ceo"]
输出:["facebook","leetcode"]

提示:

  • 1 <= words1.length, words2.length <= 104
  • 1 <= words1[i].length, words2[i].length <= 10
  • words1[i] 和 words2[i] 仅由小写英文字母组成
  • words1 中的所有字符串 互不相同

解答:

版本1:超时但是思路没问题

class Solution:
    def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
        output = []
        for item_1 in words1:
            flag_append = 1
            for item_2 in words2:
                for i in range(len(item_2)):
                    if item_2.count(item_2[i]) > item_1.count(item_2[i]):
                        flag_append = 0
                        break
                if flag_append == 0:
                    break
            if flag_append == 1:
                output.append(item_1)
        return output
    

 版本2:优化计算

class Solution:
    def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
        # preprocess words2
        max_counts = [0] * 26
        for word in words2:
            counts = [word.count(chr(i + 97)) for i in range(26)]
            for i in range(26):
                max_counts[i] = max(max_counts[i], counts[i])

        # iterate through words1
        output = []
        for word in words1:
            counts = [word.count(chr(i + 97)) for i in range(26)]
            if all(counts[i] >= max_counts[i] for i in range(26)):
                output.append(word)

        return output
    

        首先,我们使用一个长度为 26 的数组 max_counts 来存储 words2 中每个字符出现的最大计数。对于每个单词 word,我们计算它包含每个字符的计数,然后检查是否满足要求。如果 word 中包含 words2 中的每个字符且计数不小于该字符在 words2 中出现的最大计数,那么就将 word 添加到输出列表中。这样可以避免嵌套循环,提高算法的效率。

你可能感兴趣的:(力扣刷题,leetcode,算法,python)