-
Notifications
You must be signed in to change notification settings - Fork 1
/
implement-trie-prefix-tree.go
98 lines (86 loc) · 1.78 KB
/
implement-trie-prefix-tree.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* Copyright (C) 2018 all rights reserved.
*
* Author: Houmin Wei <[email protected]>
*
* Source: https://leetcode.com/problems/implement-trie-prefix-tree/description
* Description:
* Implement a trie with `insert`, `search`, and `startsWith` methods.
*
*/
package main
import (
"fmt"
)
type Trie struct {
children map[string]*Trie
isEnd bool
}
/** Initialize you data structure here. */
func Constructor() Trie {
trie := Trie{
children: make(map[string]*Trie),
isEnd: false,
}
return trie
}
/** Insert a word into the trie. */
func (this *Trie) Insert(word string) {
node := this
last := len(word) - 1
for i, c := range word {
ch := string(c)
newNode, ok := node.children[ch]
if !ok {
newNode = &Trie{children: make(map[string]*Trie), isEnd: false}
node.children[ch] = newNode
}
node = newNode
if i == last {
node.isEnd = true
}
}
}
/** Return if the word is in the trie. */
func (this *Trie) Search(word string) bool {
node := this
for _, c := range word {
ch := string(c)
newNode, ok := node.children[ch]
if !ok {
return false
}
node = newNode
}
return node.isEnd
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
node := this
for _, c := range prefix {
ch := string(c)
newNode, ok := node.children[ch]
if !ok {
return false
}
node = newNode
}
return true
}
func main() {
trie := Constructor()
trie.Insert("apple")
if trie.Search("apple") == true {
fmt.Println("find word apple")
}
if trie.Search("app") == false {
fmt.Println("could not find word app")
}
if trie.StartsWith("app") == true {
fmt.Println("find word start with app")
}
trie.Insert("app")
if trie.Search("app") == true {
fmt.Println("find word app")
}
}