Skip to content

Commit a06bd33

Browse files
committed
Update index.go
1 parent 320efd7 commit a06bd33

File tree

1 file changed

+30
-11
lines changed

1 file changed

+30
-11
lines changed

implement-trie-prefix-tree/index.go

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,43 @@
11
package implement_trie_prefix_tree
2-
type Trie struct {
32

3+
type Trie struct {
4+
children [26]*Trie
5+
isEnd bool
46
}
57

6-
78
func Constructor() Trie {
8-
9+
return Trie{}
910
}
1011

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
1422
}
1523

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
1934
}
2035

36+
func (t *Trie) Search(word string) bool {
37+
node := t.SearchPrefix(word)
38+
return node != nil && node.isEnd
39+
}
2140

22-
func (this *Trie) StartsWith(prefix string) bool {
23-
41+
func (t *Trie) StartsWith(prefix string) bool {
42+
return t.SearchPrefix(prefix) != nil
2443
}

0 commit comments

Comments
 (0)