use std::collections::HashMap;
struct TrieNode {
children: HashMap<char, Box<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(|| Box::new(TrieNode::new()));
}
node.is_end = true;
}
fn starts_with(&self, prefix: &str) -> bool {
let mut node = &self.root;
for ch in prefix.chars() {
match node.children.get(&ch) {
Some(next_node) => node = next_node.as_ref(),
None => return false,
}
}
true
}
}
fn main() {
let mut trie = Trie::new();
let mut hashmap = HashMap::new();
let words = vec!["apple", "apt", "bat"];
for &word in &words {
trie.insert(word);
hashmap.insert(word, true);
}
println!("Trie starts_with 'ap': {}", trie.starts_with("ap"));
println!("HashMap contains keys starting with 'ap':");
for key in hashmap.keys() {
if key.starts_with("ap") {
println!("{}", key);
}
}
}node = node.children.entry(ch).or_insert_with(|| Box::new(TrieNode::new()));
advance or create child node for current letter to build word path
mark end of word at last letter node
for ch in prefix.chars() { match node.children.get(&ch) { Some(next_node) => node = next_node.as_ref(), None => return false, } }
traverse trie nodes following prefix letters to check prefix existence
for &word in &words { trie.insert(word); hashmap.insert(word, true); }
insert words into both trie and hash map for comparison
for key in hashmap.keys() { if key.starts_with("ap") { println!("{}", key); } }
simulate prefix search in hash map by checking all keys
Trie starts_with 'ap': true
HashMap contains keys starting with 'ap':
apple
apt