|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +struct WordDictionary { |
| 4 | + trie: Box<Trie>, |
| 5 | +} |
| 6 | + |
| 7 | +struct Trie { |
| 8 | + ended: bool, |
| 9 | + children: HashMap<char, Box<Trie>>, |
| 10 | +} |
| 11 | + |
| 12 | + |
| 13 | +/** |
| 14 | + * `&self` means the method takes an immutable reference. |
| 15 | + * If you need a mutable reference, change it to `&mut self` instead. |
| 16 | + */ |
| 17 | +impl WordDictionary { |
| 18 | + |
| 19 | + fn new() -> Self { |
| 20 | + WordDictionary { |
| 21 | + trie: Box::new(Trie::new()), |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + // T(n) = S(n) = O(26n) = O(n) |
| 26 | + fn add_word(&mut self, word: String) { |
| 27 | + let mut t = &mut self.trie; |
| 28 | + for c in word.chars() { |
| 29 | + t = t.children |
| 30 | + .entry(c) |
| 31 | + .or_insert(Box::new(Trie::new())) |
| 32 | + } |
| 33 | + t.ended = true |
| 34 | + } |
| 35 | + |
| 36 | + fn search(&self, word: String) -> bool { |
| 37 | + return Self::search_from_index(&self.trie, &word) |
| 38 | + } |
| 39 | + |
| 40 | + // T(n) = S(n) = ((2^2)n) = O(n) |
| 41 | + fn search_from_index(trie: &Trie, word: &str) -> bool { |
| 42 | + return match word.chars() |
| 43 | + .next() { |
| 44 | + None => trie.ended, |
| 45 | + Some(c) => if c == '.' { |
| 46 | + trie.children |
| 47 | + .values() |
| 48 | + .any(|x| Self::search_from_index(&x, &word[1..])) // Slice O(1) |
| 49 | + } else { |
| 50 | + match trie.children |
| 51 | + .get(&c) { |
| 52 | + None => false, |
| 53 | + Some(x) => Self::search_from_index(&x, &word[1..]), // Slice O(1) |
| 54 | + } |
| 55 | + }, |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * Your WordDictionary object will be instantiated and called as such: |
| 62 | + * let obj = WordDictionary::new(); |
| 63 | + * obj.add_word(word); |
| 64 | + * let ret_2: bool = obj.search(word); |
| 65 | + */ |
| 66 | + |
| 67 | +impl Trie { |
| 68 | + fn new() -> Self { |
| 69 | + Trie { |
| 70 | + ended: false, |
| 71 | + children: HashMap::new(), |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments