Skip to content

Commit 512ac8c

Browse files
Merge pull request wangzheng0822#383 from caitlingao/feat-rust-35-trie
feat(geektime_algo): add 35 trie
2 parents 916244d + 9803c0c commit 512ac8c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

rust/35_trie/trie.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// [leetcode 208](https://leetcode.com/problems/implement-trie-prefix-tree/)
2+
3+
#[derive(Default, Debug)]
4+
struct Trie {
5+
is_ending: bool,
6+
nodes: [Option<Box<Trie>>; 26],
7+
}
8+
9+
impl Trie {
10+
fn new() -> Self {
11+
Default::default()
12+
}
13+
14+
fn insert(&mut self, word: &str) {
15+
let mut curr = self;
16+
for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) {
17+
curr = curr.nodes[i].get_or_insert_with(|| Box::new(Trie::new()));
18+
}
19+
curr.is_ending = true;
20+
}
21+
22+
fn find(&self, word: &str) -> bool {
23+
let mut curr = self;
24+
for i in word.chars().map(|c| (c as usize - 'a' as usize) as usize) {
25+
match curr.nodes[i].as_ref() {
26+
Some(node) => { curr = node; },
27+
None => { return false; },
28+
}
29+
}
30+
curr.is_ending
31+
}
32+
}
33+
34+
fn main() {
35+
let mut m = Trie::new();
36+
m.insert("hello");
37+
m.insert("she");
38+
println!("{:?}", m);
39+
let r = m.search("hello");
40+
println!("{}", r); // true
41+
}

0 commit comments

Comments
 (0)