@@ -2039,3 +2039,41 @@ class Solution:
2039
2039
2040
2040
return answer
2041
2041
```
2042
+
2043
+ ### 1178. 猜字谜
2044
+
2045
+ [ 原题链接] ( https://leetcode-cn.com/contest/weekly-contest-152/problems/number-of-valid-words-for-each-puzzle/ )
2046
+
2047
+ #### 思路
2048
+
2049
+ 一般会想到的思路:遍历 ` puzzles ` ,在每次遍历中再遍历 ` words ` ,寻找到可行的谜底。但 ` 1 <= words.length <= 10^5 ` 且 ` 1 <= puzzles.length <= 10^4 ` ,这样做的话显然是会超时的。
2050
+
2051
+ 我们注意到 ` puzzles[i].length == 7 ` ,那么 ` puzzles[i] ` 的谜底不会超过 2^7 = 128 因此我们可以直接枚举出 ` puzzles[i] ` 对应的谜底,然后遍历所有的谜底,看该谜底是否在 ` words ` 出现。
2052
+
2053
+ ``` python
2054
+ class Solution :
2055
+ def findNumOfValidWords (self , words : List[str ], puzzles : List[str ]) -> List[int ]:
2056
+ # word 统计
2057
+ word_dict = dict ()
2058
+ for word in words:
2059
+ tmp = ' ' .join(sorted (list (set (word))))
2060
+ if len (tmp) <= 7 :
2061
+ word_dict[tmp] = word_dict.get(tmp, 0 ) + 1
2062
+
2063
+ p_length = len (puzzles)
2064
+ answer = [0 for _ in range (p_length)]
2065
+ p_list = [[] for _ in range (p_length)]
2066
+ # 算出 puzzle 对应的谜面集合
2067
+ for i in range (p_length):
2068
+ puzzle = puzzles[i]
2069
+ p_list[i] = [puzzle[0 ]]
2070
+ for c in puzzle[1 :]:
2071
+ p_list[i] += [' ' .join(sorted (s + c)) for s in p_list[i]]
2072
+
2073
+ for i in range (p_length):
2074
+ answers = p_list[i]
2075
+ for ans in answers:
2076
+ answer[i] += word_dict.get(ans, 0 )
2077
+
2078
+ return answer
2079
+ ```
0 commit comments