This repository has been archived by the owner on Dec 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement-magic-dictionary.rs
75 lines (68 loc) · 1.97 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
struct MagicDictionary {
vec: 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 { vec: vec![] }
}
fn build_dict(&mut self, dictionary: Vec<String>) {
self.vec.extend(dictionary);
}
fn search(&self, search_word: String) -> bool {
let len = search_word.len();
let words = search_word.bytes();
for i in self.vec.iter().filter(|x| x.len() == len) {
let mut num = 0;
for (a, b) in i.bytes().zip(words.clone()) {
if a != b {
num += 1;
}
}
if num == 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);
*/
fn main() {
let mut obj = MagicDictionary::new();
obj.build_dict(vec![
"hello".to_string(),
"leetcode".to_string(),
"judge".to_string(),
]);
println!("{}", obj.search("hello".to_string()));
println!("{}", obj.search("hhllo".to_string()));
println!("{}", obj.search("hell".to_string()));
println!("{}", obj.search("leetcoded".to_string()));
println!("{}", obj.search("judge".to_string()));
}
#[cfg(test)]
mod tests {
use crate::MagicDictionary;
#[test]
fn test() {
let mut obj = MagicDictionary::new();
obj.build_dict(vec![
"hello".to_string(),
"leetcode".to_string(),
"judge".to_string(),
]);
assert!(!obj.search("hello".to_string()));
assert!(obj.search("hhllo".to_string()));
assert!(!obj.search("hell".to_string()));
assert!(!obj.search("leetcoded".to_string()));
assert!(!obj.search("judge".to_string()));
}
}