LeetCode題解(1178):猜字謎(Python)

長行發表於2020-11-26

題目:原題連結(困難)

標籤:雜湊表、位運算

解法時間複雜度空間複雜度執行用時
Ans 1 (Python) O ( W × L × l o g L + P × 2 7 × 7 × l o g 7 ) O(W×L×logL+P×2^7×7×log7) O(W×L×logL+P×27×7×log7) : 其中L為謎底長度 O ( W × L + 2 7 × 7 ) O(W×L+2^7×7) O(W×L+27×7)916ms (35.29%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Solution:
    def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:
        def all_chance(chars):
            lst = [chars[0]]
            chars = list(sorted(set(chars[1:])))
            size = len(chars)
            res = []

            def recursion(i):
                if i == size:
                    res.append("".join(sorted(lst)))
                else:
                    lst.append(chars[i])
                    recursion(i + 1)
                    lst.pop()
                    recursion(i + 1)

            recursion(0)

            return res

        count = collections.Counter()
        for word in words:
            count["".join(sorted(set(word)))] += 1

        ans = []
        for puzzle in puzzles:
            now = 0
            for chance in all_chance(puzzle):
                now += count[chance]
            ans.append(now)

        return ans

相關文章