32 lines
1008 B
Rust
32 lines
1008 B
Rust
|
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
|
||
|
}
|
||
|
}
|