1use std::collections::HashMap;
2
3pub struct Trie {
14 prefix: String,
15 children: HashMap<char, Self>,
16 is_terminal: bool,
17}
18
19impl Trie {
20 pub fn new() -> Self {
22 Self::with_prefix("", true )
23 }
24
25 pub fn with_prefix(s: &str, is_terminal: bool) -> Self {
28 Self {
29 prefix: s.to_owned(),
30 children: HashMap::new(),
31 is_terminal,
32 }
33 }
34
35 pub fn insert(&mut self, word: &str) {
37 let mut curr = self;
38 let chars: Vec<_> = word.chars().collect();
39 for (i, c) in chars.iter().enumerate() {
40 let is_terminal = i == chars.len() - 1;
41 curr = curr
42 .children
43 .entry(*c)
44 .and_modify(|t| t.is_terminal |= is_terminal)
45 .or_insert(Self::with_prefix(&word[..=i], is_terminal));
46 }
47 }
48
49 pub fn find(&self, word: &str) -> Option<&Self> {
53 let mut curr = self;
54 for c in word.chars() {
55 let t = curr.children.get(&c)?;
56 curr = t;
57 }
58
59 Some(curr)
60 }
61
62 pub fn contains(&self, word: &str) -> bool {
64 let Some(node) = self.find(word) else {
65 return false;
66 };
67
68 node.is_terminal()
69 }
70
71 pub fn is_terminal(&self) -> bool {
72 self.is_terminal
73 }
74
75 pub fn prefix(&self) -> &str {
76 &self.prefix
77 }
78}
79
80impl Default for Trie {
81 fn default() -> Self {
82 Self::new()
83 }
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89
90 #[test]
91 fn test_empty() {
92 let t = Trie::new();
93 assert!(t.contains(""));
94 assert!(!t.contains("a"));
95 }
96
97 #[test]
98 fn test_typical() {
99 let mut t = Trie::new();
100 assert!(t.contains(""));
101
102 t.insert("asdf");
103 t.insert("1234");
104 t.insert("asteroid");
105 t.insert("astronaut");
106 t.insert("1235");
107
108 assert!(t.contains(""));
109 assert!(t.contains("asdf"));
110 assert!(t.contains("1234"));
111 assert!(t.contains("asteroid"));
112 assert!(t.contains("astronaut"));
113 assert!(t.contains("1235"));
114
115 assert!(!t.contains("as"));
116 t.insert("as");
117 assert!(t.contains("as"));
118 assert!(t.contains("asteroid"));
119 assert!(t.contains("astronaut"));
120 assert!(t.contains("asdf"));
121 }
122}