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 are no valid words for"gaswxyz" cause none of the words in the list contains letter 'g'.
Each word and puzzle can be represented as a bitmask. For each puzzle, enumerate all its subsets that include the first letter, and count how many words have the same bitmask.
classSolution {
public: vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) {
unordered_map<int, int> freq;
for (auto& w : words) {
int mask =0;
for (char c : w) mask |=1<< (c -'a');
freq[mask]++;
}
vector<int> ans;
for (auto& p : puzzles) {
int mask =0;
for (char c : p) mask |=1<< (c -'a');
int first =1<< (p[0] -'a');
int sub = mask, cnt =0;
do {
if (sub & first) cnt += freq[sub];
sub = (sub -1) & mask;
} while (sub != mask);
ans.push_back(cnt);
}
return ans;
}
};
classSolution {
funfindNumOfValidWords(words: Array<String>, puzzles: Array<String>): List<Int> {
val freq = mutableMapOf<Int, Int>()
for (w in words) {
var mask = 0for (c in w) mask = mask or (1 shl (c - 'a'))
freq[mask] = freq.getOrDefault(mask, 0) + 1 }
val ans = mutableListOf<Int>()
for (p in puzzles) {
var mask = 0for (c in p) mask = mask or (1 shl (c - 'a'))
val first = 1 shl (p[0] - 'a')
var sub = mask; var cnt = 0do {
if ((sub and first) !=0) cnt += freq.getOrDefault(sub, 0)
sub = (sub - 1) and mask
} while (sub != mask)
ans.add(cnt)
}
return ans
}
}
classSolution:
deffindNumOfValidWords(self, words: list[str], puzzles: list[str]) -> list[int]:
from collections import Counter
freq = Counter()
for w in words:
mask =0for c in set(w):
mask |=1<< (ord(c)-97)
freq[mask] +=1 ans = []
for p in puzzles:
mask =0for c in p:
mask |=1<< (ord(c)-97)
first =1<< (ord(p[0])-97)
sub = mask
cnt =0whileTrue:
if sub & first:
cnt += freq[sub]
if sub ==0:
break sub = (sub-1) & mask
ans.append(cnt)
return ans
use std::collections::HashMap;
impl Solution {
pubfnfind_num_of_valid_words(words: Vec<String>, puzzles: Vec<String>) -> Vec<i32> {
letmut freq = HashMap::new();
for w in words.iter() {
letmut mask =0;
for c in w.chars() { mask |=1<< (c asu8-b'a'); }
*freq.entry(mask).or_insert(0) +=1;
}
letmut ans = Vec::with_capacity(puzzles.len());
for p in puzzles.iter() {
letmut mask =0;
for c in p.chars() { mask |=1<< (c asu8-b'a'); }
let first =1<< (p.chars().next().unwrap() asu8-b'a');
letmut sub = mask;
letmut cnt =0;
loop {
if sub & first !=0 { cnt +=*freq.get(&sub).unwrap_or(&0); }
if sub ==0 { break; }
sub = (sub-1) & mask;
}
ans.push(cnt);
}
ans
}
}