forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0211-design-add-and-search-words-data-structure.rs
60 lines (49 loc) · 1.46 KB
/
0211-design-add-and-search-words-data-structure.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
#[derive(Default)]
struct WordDictionary {
is_word_end: bool,
children: [Option<Box<WordDictionary>>; 26],
}
impl WordDictionary {
fn new() -> Self {
Default::default()
}
fn add_word(&mut self, word: String) {
let mut dict = self;
for c in word.chars(){
dict = dict.children[char_index(c)]
.get_or_insert(Box::new(WordDictionary::new()))
.as_mut();
}
dict.is_word_end = true;
}
fn search_ref(&self, word: &str) -> bool{
let mut dict = self;
for (i, c) in word.chars().enumerate(){
if c == '.'{
let res = dict.children
.iter()
.any(|opt|{
if let Some(ref next_dict) = opt{
next_dict.search_ref(&word[i + 1..])
}else{
false
}
});
return res;
}else{
if let Some(ref next_dict) = dict.children[char_index(c)]{
dict = next_dict.as_ref();
}else{
return false;
}
}
}
dict.is_word_end
}
fn search(&self, word: String) -> bool {
self.search_ref(&word)
}
}
pub fn char_index(c: char) -> usize{
c as usize - 'a' as usize
}