use std::collections::HashMap;
struct TrieNode {
children: HashMap<char, TrieNode>,
is_end: bool,
}
impl TrieNode {
fn new() -> Self {
TrieNode {
children: HashMap::new(),
is_end: false,
}
}
}
struct Trie {
root: TrieNode,
}
impl Trie {
fn new() -> Self {
Trie {
root: TrieNode::new(),
}
}
fn insert(&mut self, word: &str) {
let mut node = &mut self.root;
for ch in word.chars() {
node = node.children.entry(ch).or_insert_with(TrieNode::new); // advance or create child
}
node.is_end = true; // mark end of word
}
fn search_prefix_node(&self, prefix: &str) -> Option<&TrieNode> {
let mut node = &self.root;
for ch in prefix.chars() {
match node.children.get(&ch) {
Some(next_node) => node = next_node, // advance to next node
None => return None, // prefix not found
}
}
Some(node) // return node at prefix end
}
fn collect_words(&self, node: &TrieNode, prefix: &mut String, results: &mut Vec<String>) {
if node.is_end {
results.push(prefix.clone()); // found a word
}
for (ch, child) in &node.children {
prefix.push(*ch); // add char
self.collect_words(child, prefix, results); // recurse
prefix.pop(); // backtrack
}
}
fn starts_with(&self, prefix: &str) -> Vec<String> {
let mut results = Vec::new();
if let Some(node) = self.search_prefix_node(prefix) {
let mut prefix_string = prefix.to_string();
self.collect_words(node, &mut prefix_string, &mut results); // gather words
}
results
}
}
fn main() {
let mut trie = Trie::new();
trie.insert("man");
trie.insert("map");
trie.insert("made");
let prefix = "ma";
let words = trie.starts_with(prefix);
println!("Words starting with '{}': {}", prefix, words.join(", "));
}node = node.children.entry(ch).or_insert_with(TrieNode::new);
advance or create child node for current character
mark current node as end of a word
match node.children.get(&ch) { ... }
traverse children to find prefix path
results.push(prefix.clone());
add found word to results when end node reached
self.collect_words(child, prefix, results);
recursively collect all words below current node
Words starting with 'ma': man, map, made