Number of Valid Words for Each Puzzle LeetCode solution in Python
1class Solution:2def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:3look_up = collections.defaultdict(int)45def get_mask(word):6mask = 07for c in word:8mask |= 1 << (ord(c) - ord("a"))9return mask1011for word in words:12mask = get_mask(word)13look_up[mask] += 114ans = []1516def solve(puzzle_idx, mask, c_idx):17if c_idx == len(puzzles[puzzle_idx]):18ans[-1] += look_up[mask]19return20# take this c_idx21solve(22puzzle_idx,23mask | 1 << (ord(puzzles[puzzle_idx][c_idx]) - ord("a")),24c_idx + 1,25)26# dont take this c_idx27solve(puzzle_idx, mask, c_idx + 1)2829for i, puzzle in enumerate(puzzles):30ans.append(0)31solve(i, 1 << (ord(puzzle[0]) - ord("a")), 1)32return ans