-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path11-implement-magic-dictionary.rs
52 lines (44 loc) · 1.21 KB
/
11-implement-magic-dictionary.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
// https://leetcode.cn/problems/implement-magic-dictionary/
struct MagicDictionary {
dictionary: Vec<String>
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MagicDictionary {
fn new() -> Self {
Self {
dictionary: vec![]
}
}
fn build_dict(&mut self, dictionary: Vec<String>) {
self.dictionary = dictionary;
}
fn search(&self, search_word: String) -> bool {
for word in &self.dictionary {
if word.len() != search_word.len() {
continue;
}
let mut diff = 0;
for i in 0..word.len() {
if word.as_bytes()[i] != search_word.as_bytes()[i] {
diff += 1;
if diff > 1 {
break;
}
}
}
if diff == 1 {
return true;
}
}
false
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* let obj = MagicDictionary::new();
* obj.build_dict(dictionary);
* let ret_2: bool = obj.search(searchWord);
*/