File tree Expand file tree Collapse file tree 1 file changed +30
-11
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +30
-11
lines changed Original file line number Diff line number Diff line change 1
1
package implement_trie_prefix_tree
2
- type Trie struct {
3
2
3
+ type Trie struct {
4
+ children [26 ]* Trie
5
+ isEnd bool
4
6
}
5
7
6
-
7
8
func Constructor () Trie {
8
-
9
+ return Trie {}
9
10
}
10
11
11
-
12
- func (this * Trie ) Insert (word string ) {
13
-
12
+ func (t * Trie ) Insert (word string ) {
13
+ node := t
14
+ for _ , ch := range word {
15
+ ch -= 'a'
16
+ if node .children [ch ] == nil {
17
+ node .children [ch ] = & Trie {}
18
+ }
19
+ node = node .children [ch ]
20
+ }
21
+ node .isEnd = true
14
22
}
15
23
16
-
17
- func (this * Trie ) Search (word string ) bool {
18
-
24
+ func (t * Trie ) SearchPrefix (prefix string ) * Trie {
25
+ node := t
26
+ for _ , ch := range prefix {
27
+ ch -= 'a'
28
+ if node .children [ch ] == nil {
29
+ return nil
30
+ }
31
+ node = node .children [ch ]
32
+ }
33
+ return node
19
34
}
20
35
36
+ func (t * Trie ) Search (word string ) bool {
37
+ node := t .SearchPrefix (word )
38
+ return node != nil && node .isEnd
39
+ }
21
40
22
- func (this * Trie ) StartsWith (prefix string ) bool {
23
-
41
+ func (t * Trie ) StartsWith (prefix string ) bool {
42
+ return t . SearchPrefix ( prefix ) != nil
24
43
}
You can’t perform that action at this time.
0 commit comments