31 lines
635 B
Rust
31 lines
635 B
Rust
|
|
use std::collections::HashMap;
|
||
|
|
|
||
|
|
#[derive(Default, Debug, Clone)]
|
||
|
|
struct Node {
|
||
|
|
end: bool,
|
||
|
|
children: HashMap<char, Node>,
|
||
|
|
}
|
||
|
|
#[derive(Default, Debug, Clone)]
|
||
|
|
pub struct Trie {
|
||
|
|
root: Node,
|
||
|
|
}
|
||
|
|
impl Trie {
|
||
|
|
pub fn insert(&mut self, word: &str) {
|
||
|
|
let mut node = &mut self.root;
|
||
|
|
for char in word.chars() {
|
||
|
|
node = node.children.entry(char).or_default();
|
||
|
|
}
|
||
|
|
node.end = true;
|
||
|
|
}
|
||
|
|
pub fn contains(&self, word: &str) -> bool {
|
||
|
|
let mut current_node = &self.root;
|
||
|
|
for char in word.chars() {
|
||
|
|
match current_node.children.get(&char) {
|
||
|
|
Some(node) => current_node = node,
|
||
|
|
None => return false,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
current_node.end
|
||
|
|
}
|
||
|
|
}
|