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
| class Solution { public: vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) { unordered_map<int, int> frequency; for (const string& word: words) { int mask = 0; for (char ch: word) mask |= (1 << (ch - 'a')); if (__builtin_popcount(mask) <= 7) ++frequency[mask]; } vector<int> ans; for (const string& puzzle: puzzles) { int cnt = 0; int mask = 0; for (int i = 1; i < 7; ++i) mask |= (1 << (puzzle[i] - 'a')); int subset = mask; do { int s = subset | (1 << (puzzle[0] - 'a')); if (frequency.find(s) != frequency.end()) cnt += frequency[s]; subset = (subset - 1) & mask; } while (subset != mask); ans.emplace_back(cnt); } return ans; } };
|