-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths0208_implement_trie_prefix_tree.rs
78 lines (68 loc) · 1.85 KB
/
s0208_implement_trie_prefix_tree.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#![allow(unused)]
// amazon interview
#[derive(Default)]
struct Trie {
children: [Option<Box<Trie>>; 26],
end: bool,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl Trie {
/** Initialize your data structure here. */
fn new() -> Self {
Default::default()
}
/** Inserts a word into the trie. */
fn insert(&mut self, word: String) {
let mut node = self;
for &c in word.as_bytes() {
node = node.children[(c - b'a') as usize].get_or_insert(Box::new(Default::default()));
}
node.end = true;
}
/** Returns if the word is in the trie. */
fn search(&self, word: String) -> bool {
let mut cur = self;
for i in word.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) {
match cur.children[i].as_ref() {
Some(node) => {
cur = node;
}
None => {
return false;
}
}
}
cur.end
}
/** Returns if there is any word in the trie that starts with the given prefix. */
fn starts_with(&self, prefix: String) -> bool {
let mut cur = self;
for i in prefix.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) {
match cur.children[i].as_ref() {
Some(node) => {
cur = node;
}
None => {
return false;
}
}
}
true
}
}
/**
* Your Trie object will be instantiated and called as such:
* let obj = Trie::new();
* obj.insert(word);
* let ret_2: bool = obj.search(word);
* let ret_3: bool = obj.starts_with(prefix);
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_208() {}
}