leetcode每日一题—1178.猜字谜

题目:
外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。

字谜的迷面 puzzle 按字符串形式给出,如果一个单词 word 符合下面两个条件,那么它就可以算作谜底:

单词 word 中包含谜面 puzzle 的第一个字母。
单词 word 中的每一个字母都可以在谜面 puzzle 中找到。
例如,如果字谜的谜面是 “abcdefg”,那么可以作为谜底的单词有 “faced”, “cabbage”, 和 “baggage”;而 “beefed”(不含字母 “a”)以及 “based”(其中的 “s” 没有出现在谜面中)。
返回一个答案数组 answer,数组中的每个元素 answer[i] 是在给出的单词列表 words 中可以作为字谜迷面 puzzles[i] 所对应的谜底的单词数目。
leetcode每日一题—1178.猜字谜_第1张图片
思路:
|:python中的位运算“或”

解答:
方法一:超时

class Solution:
    def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
        pl=len(puzzles)
        res=[0]*pl
        i=0
        for puzzle in puzzles:
            for word in words:
                if puzzle[0] in word:
                    counter=collections.Counter(word)
                    flag=False
                    for k in counter.keys():
                        if k not in puzzle:
                            flag=True
                            break
                    if not flag:
                        res[i]+=1   
            i+=1
        return res

方法二:压缩优化
参考:https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle/solution/zhuang-tai-ya-suo-zi-ji-ti-jie-yi-dong-c-bdx8/

class Solution:
    def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
        freq = collections.Counter()
        for word in words:
            mask = 0
            for c in word:
                mask |= 1 << (ord(c) - ord('a'))
            freq[mask] += 1
        res = []
        for puzzle in puzzles:
            total = 0
            for perm in self.subsets(puzzle[1:]):
                mask = 1 << (ord(puzzle[0]) - ord('a'))
                for c in perm:
                    mask |= 1 << (ord(c) - ord('a'))
                total += freq[mask]
            res.append(total)
        return res
    
    #求所给单词的全排列
    def subsets(self, word: List[int]) -> List[List[int]]:
        res = [""]
        for i in word:
            res = res + [i + c for c in res]
        return res

你可能感兴趣的:(leetcode,Python)