Skip to content

Commit

Permalink
71: Submit
Browse files Browse the repository at this point in the history
  • Loading branch information
sankichi92 committed Dec 31, 2023
1 parent d5da679 commit d353529
Showing 1 changed file with 13 additions and 64 deletions.
77 changes: 13 additions & 64 deletions 71-search-suggestions-system/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,70 +1,19 @@
use std::collections::HashMap;
pub fn suggested_products(mut products: Vec<String>, search_word: String) -> Vec<Vec<String>> {
products.sort_unstable();

#[derive(Debug)]
struct Trie {
children: HashMap<char, Box<Trie>>,
}

impl Trie {
fn new() -> Self {
Trie {
children: HashMap::new(),
}
}

fn build(words: Vec<String>) -> Self {
let mut children = HashMap::new();
for word in words {
let mut chars = word.chars();
let mut current = children
.entry(chars.next().unwrap())
.or_insert(Box::new(Trie::new()));
for char in chars {
current = current
.children
.entry(char)
.or_insert(Box::new(Trie::new()));
}
}
Trie { children }
}

fn words(&self, mut prefix: String) -> Vec<String> {
if self.children.is_empty() {
return vec![prefix.to_string()];
}

let mut results = vec![];
for (char, trie) in self.children.iter() {
prefix.push(*char);
let mut words = trie.words(prefix.clone());
words.sort();
results.extend(words.into_iter().take(3));
}

results
}
}

pub fn suggested_products(products: Vec<String>, search_word: String) -> Vec<Vec<String>> {
let mut results = vec![];

let trie = Trie::build(products);
println!("{:?}", trie);

let mut chars = search_word.chars();
let first_char = chars.next().unwrap();
let mut current_trie = trie.children.get(&first_char);
let mut current_word = first_char.to_string();

for char in chars {
if let Some(trie) = current_trie {
results.push(trie.words(current_word.clone()));
current_trie = trie.children.get(&char);
} else {
results.push(vec![]);
}
current_word.push(char);
let mut current = "".to_string();
for char in search_word.chars() {
current.push(char);
results.push(
products
.iter()
.filter(|product| product.starts_with(&current))
.take(3)
.cloned()
.collect(),
);
}

results
Expand Down

0 comments on commit d353529

Please sign in to comment.