leet-code/maximum-product-of-word-len.../sol.rs

32 lines
1008 B
Rust
Raw Permalink Normal View History

2022-05-29 19:21:38 +00:00
use std::collections::HashMap;
impl Solution {
#[inline]
pub fn letter_bitmap(word: &str) -> u32 {
word.bytes()
.fold(0u32, |bitmap, chr| bitmap | (1 << (chr-97)))
}
pub fn max_product(words: Vec<String>) -> i32 {
let vals: HashMap<u32, usize> = words
.iter()
.fold(HashMap::new(), |mut vals, word| {
let bitmap = Solution::letter_bitmap(word);
vals.insert(bitmap, word.len().max(*vals.get(&bitmap).unwrap_or(&0)));
vals
});
vals.iter()
.map(|(&bitmap1, &value1)| {
vals.iter()
.filter_map(|(&bitmap2, &value2)| {
if bitmap1 & bitmap2 == 0 {
return Some(value1*value2);
}
None
})
.max()
.unwrap_or(0)
})
.max().unwrap_or(0) as i32
}
}