use std::collections::HashMap;
struct TrieNode {
children: HashMap<char, Box<TrieNode>>,
is_end_of_word: bool,
}
impl TrieNode {
fn new() -> Self {
TrieNode {
children: HashMap::new(),
is_end_of_word: false,
}
}
}
struct Trie {
root: TrieNode,
}
impl Trie {
fn new() -> Self {
Trie {
root: TrieNode::new(),
}
}
fn insert(&mut self, word: &str) {
let mut current = &mut self.root;
for ch in word.chars() {
current = current.children.entry(ch).or_insert_with(|| Box::new(TrieNode::new()));
}
current.is_end_of_word = true;
}
fn search(&self, word: &str) -> bool {
let mut current = &self.root;
for ch in word.chars() {
match current.children.get(&ch) {
Some(node) => current = node, // advance to next letter node
None => return false, // letter not found, word missing
}
}
current.is_end_of_word // check if word ends here
}
}
fn main() {
let mut trie = Trie::new();
trie.insert("cat");
trie.insert("cars");
let word = "car";
let found = trie.search(word);
println!("Search result for '{}': {}", word, found);
}current = current.children.entry(ch).or_insert_with(|| Box::new(TrieNode::new()));
advance current to child node for letter, create if missing
match current.children.get(&ch) {
check if next letter node exists to continue search
Some(node) => current = node, // advance to next letter node
move current pointer to next letter node
None => return false, // letter not found, word missing
stop search early if letter path missing
current.is_end_of_word // check if word ends here
confirm if current node marks end of searched word
Search result for 'car': false