-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path208.实现-trie-前缀树.rs
69 lines (60 loc) · 1.49 KB
/
208.实现-trie-前缀树.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
/*
* @lc app=leetcode.cn id=208 lang=rust
*
* [208] 实现 Trie (前缀树)
*/
// @lc code=start
use::std::collections::HashMap;
struct Trie {
childs: HashMap<char ,Box<Trie>>,
is_end: bool ,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl Trie {
fn new() -> Self {
Trie{
childs:HashMap::new(),
is_end:false,
}
}
fn insert(&mut self, word: String) {
let mut node = self;
for ch in word.chars(){
node = node.childs.entry(ch).or_insert_with(|| Box::new(Trie::new()));
}
node.is_end = true;
}
fn search(&self, word: String) -> bool {
let mut node = self;
for ch in word.chars(){
if let Some(child) = node.childs.get(&ch){
node = child;
}else{
return false;
}
}
node.is_end
}
fn starts_with(&self, prefix: String) -> bool {
let mut node = self;
for ch in prefix.chars(){
if let Some(child) = node.childs.get(&ch){
node = child;
}else{
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);
*/
// @lc code=end