With respect to a given puzzle
string, a word
is valid if both the following conditions are satisfied:
word
contains the first letter ofpuzzle
.- For each letter in
word
, that letter is inpuzzle
.
For example, if the puzzle is “abcdefg”, then valid words are “faced”, “cabbage”, and “baggage”; while invalid words are “beefed” (doesn’t include “a”) and “based” (includes “s” which isn’t in the puzzle).
Return an array answer
, where answer[i]
is the number of words in the given word list words
that are valid with respect to the puzzle puzzles[i]
.
Example :
Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] Output: [1,1,3,2,4,0] Explanation: 1 valid word for "aboveyz" : "aaaa" 1 valid word for "abrodyz" : "aaaa" 3 valid words for "abslute" : "aaaa", "asas", "able" 2 valid words for "absoryz" : "aaaa", "asas" 4 valid words for "actresz" : "aaaa", "asas", "actt", "access" There're no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.
Constraints:
1 <= words.length <= 10^5
4 <= words[i].length <= 50
1 <= puzzles.length <= 10^4
puzzles[i].length == 7
words[i][j]
,puzzles[i][j]
are English lowercase letters.- Each
puzzles[i]
doesn’t contain repeated characters.
Solution: Subsets
Preprocessing:
Compress each word to a bit map, and compute the frequency of each bit map.
Since there are at most |words| bitmaps while its value ranging from 0 to 2^26, thus it’s better to use a hashtable instead of an array.
Query:
Use the same way to compress a puzzle into a bit map.
Try all subsets (at most 128) of the puzzle (the bit of the first character is be must), and check how many words match each subset.
words = [“aaaa”,”asas”,”able”,”ability”,”actt”,”actor”,”access”],
puzzle = “abslute”
bitmap(“aaaa”) = {0}
bitmap(“asas”) = {0, 18}
bitmap(“able”) = {0,1,4,11}
bitmap(“actt”) = {0, 2, 19}
bitmap(“actor”) = {0, 2, 14, 17, 19}
bitmap(“access”) = {0, 2, 4, 18}
bitmap(“abslute”) = {0, 1, 4, 11, 18, 19, 20}
Time complexity: O(sum(len(w_i)) + |puzzles|)
Space complexity: O(|words|)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// Author: Huahua, 136 ms, 29.7 MB class Solution { public: vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) { vector<int> ans; unordered_map<int, int> freq; for (const string& word : words) { int mask = 0; for (char c : word) mask |= 1 << (c - 'a'); ++freq[mask]; } for (const string& p : puzzles) { int mask = 0; for (char c : p) mask |= 1 << (c - 'a'); int first = p[0] - 'a'; int curr = mask; int total = 0; while (curr) { if ((curr >> first) & 1) { auto it = freq.find(curr); if (it != freq.end()) total += it->second; } curr = (curr - 1) & mask; } ans.push_back(total); } return ans; } }; |