|
| 1 | +/** |
| 2 | + * 1178. Number of Valid Words for Each Puzzle |
| 3 | + * https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * With respect to a given puzzle string, a word is valid if both the following conditions |
| 7 | + * are satisfied: |
| 8 | + * - word contains the first letter of puzzle. |
| 9 | + * - For each letter in word, that letter is in puzzle. |
| 10 | + * - For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", |
| 11 | + * and "baggage", while |
| 12 | + * - invalid words are "beefed" (does not include 'a') and "based" (includes 's' which |
| 13 | + * is not in the puzzle). |
| 14 | + * |
| 15 | + * Return an array answer, where answer[i] is the number of words in the given word list words |
| 16 | + * that is valid with respect to the puzzle puzzles[i]. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {string[]} words |
| 21 | + * @param {string[]} puzzles |
| 22 | + * @return {number[]} |
| 23 | + */ |
| 24 | +var findNumOfValidWords = function(words, puzzles) { |
| 25 | + const wordMasks = new Map(); |
| 26 | + for (const word of words) { |
| 27 | + const mask = getBitmask(word); |
| 28 | + wordMasks.set(mask, (wordMasks.get(mask) || 0) + 1); |
| 29 | + } |
| 30 | + |
| 31 | + const result = []; |
| 32 | + for (const puzzle of puzzles) { |
| 33 | + const puzzleMask = getBitmask(puzzle); |
| 34 | + const firstCharBit = 1 << (puzzle.charCodeAt(0) - 97); |
| 35 | + let count = 0; |
| 36 | + |
| 37 | + let submask = puzzleMask; |
| 38 | + do { |
| 39 | + if (submask & firstCharBit && wordMasks.has(submask)) { |
| 40 | + count += wordMasks.get(submask); |
| 41 | + } |
| 42 | + submask = (submask - 1) & puzzleMask; |
| 43 | + } while (submask); |
| 44 | + |
| 45 | + result.push(count); |
| 46 | + } |
| 47 | + |
| 48 | + return result; |
| 49 | + |
| 50 | + function getBitmask(str) { |
| 51 | + let mask = 0; |
| 52 | + for (const char of str) { |
| 53 | + mask |= 1 << (char.charCodeAt(0) - 97); |
| 54 | + } |
| 55 | + return mask; |
| 56 | + } |
| 57 | +}; |
0 commit comments