leet-code/search-suggestions-system/sol.rs

31 lines
1.3 KiB
Rust

impl Solution {
pub fn suggested_products(products: Vec<String>, search_word: String) -> Vec<Vec<String>> {
// Products list mapped to maximum common prefix length with search_word
let max_prefix_matches = products.iter()
.map(|product| product.bytes()
.zip(search_word.bytes())
.take_while(|&(chr1, chr2)| chr1 == chr2)
.count()
)
.collect::<Vec<_>>();
search_word.bytes()
.enumerate()
.map(|(chr_idx, chr)| {
// Get all options that match at least chr_idx prefix length
let mut options = max_prefix_matches.iter()
.enumerate()
.filter_map(|(product_idx, &max_prefix_match)| {
if max_prefix_match > chr_idx {
Some(&products[product_idx])
} else { None }
})
.collect::<Vec<_>>();
options.sort(); // TODO : Could optimise since we are only taking 3 smallest elements
options.into_iter()
.take(3)
.map(|s| s.clone())
.collect()
})
.collect()
}
}