use hashbrown::HashMap;
#[derive(Debug, Clone)]
struct Node {
children: HashMap<char, Node>,
is_end: bool,
}
impl Node {
fn new() -> Self {
Self {
children: HashMap::new(),
is_end: false,
}
}
}
#[derive(Debug, Clone)]
pub struct Trie {
root: Node,
}
impl Trie {
pub fn new() -> Self {
Self { root: Node::new() }
}
pub fn insert<S: AsRef<str>>(&mut self, word: S) {
let mut current = &mut self.root;
for c in word.as_ref().chars() {
current = current.children.entry(c).or_insert(Node::new());
}
current.is_end = true;
}
pub fn search<S: AsRef<str>>(&mut self, word: S) -> bool {
let mut current = &self.root;
for c in word.as_ref().chars() {
if let Some(node) = current.children.get(&c) {
current = node;
} else {
return false;
}
}
current.is_end
}
}
impl Default for Trie {
fn default() -> Self {
Self::new()
}
}