LeetCode Entry
1684. Count the Number of Consistent Strings
Count words with allowed characters
1684. Count the Number of Consistent Strings easy
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/732
Problem TLDR
Count words with allowed characters #easy
Intuition
There are total of 26 characters, check them.
Approach
- we can use a HashSet
- we can use a bit mask
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
fun countConsistentStrings(allowed: String, words: Array<String>) =
words.count { it.all { it in allowed }}
pub fn count_consistent_strings(allowed: String, words: Vec<String>) -> i32 {
let set: HashSet<_> = allowed.bytes().collect();
words.iter().filter(|w| w.bytes().all(|b| set.contains(&b))).count() as _
}
int countConsistentStrings(string allowed, vector<string>& words) {
auto bits = [](string w) {
int mask = 0; for (int i = 0; i < w.length(); i++)
mask |= 1 << (w[i] - 'a');
return mask;
};
int mask = bits(allowed);
return std::count_if(words.begin(), words.end(),
[mask, &bits](string w){return (mask | bits(w)) == mask;});
}