#1160
Easy Algorithms Find words that can be formed by characters
Array Hash Table String Counting
71.5% acceptance
Feb 25, 2026
2250
189
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once for each word in words).
Return the sum of lengths of all good strings in words.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn count_characters(words: Vec<String>, chars: String) -> i32 {
let mut chars_count = [0u32; 26];
for c in chars.bytes() { chars_count[(c - b'a') as usize] += 1; }
let mut result = 0;
'outer: for word in &words {
let mut wc = [0u32; 26];
for c in word.bytes() { wc[(c - b'a') as usize] += 1; }
for i in 0..26 {
if wc[i] > chars_count[i] { continue 'outer; }
}
result += word.len() as i32;
}
result
}
}