File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments