-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path0211.rs
58 lines (51 loc) · 1.33 KB
/
0211.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
#[derive(Default)]
struct TrieNode {
child: [Option<Box<TrieNode>>; 26],
is_end: bool,
}
#[derive(Default)]
struct WordDictionary {
trie: TrieNode,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl WordDictionary {
fn new() -> Self {
Default::default()
}
fn add_word(&mut self, word: String) {
let mut node = &mut self.trie;
for &c in word.as_bytes() {
node = node.child[(c - b'a') as usize].get_or_insert(Box::new(Default::default()));
}
node.is_end = true;
}
fn search(&self, word: String) -> bool {
return dfs(word.as_bytes(), 0, &self.trie);
}
}
fn dfs(word: &[u8], index: usize, node: &TrieNode) -> bool {
if index == word.len() {
return node.is_end;
}
let &c = word.get(index).unwrap();
if c >= b'a' && c <= b'z' {
let ci = (c - b'a') as usize;
if let Some(t) = &node.child[ci] {
if dfs(word, index + 1, t) {
return true;
}
}
} else if c == b'.' {
for child in node.child.iter() {
if let Some(t) = child {
if dfs(word, index + 1, t) {
return true;
}
}
}
}
false
}