forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.go
46 lines (42 loc) · 891 Bytes
/
trie.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
// Package trie provides Trie data structures in golang.
//
// Wikipedia: https://en.wikipedia.org/wiki/Trie
package trie
// Node represents each node in Trie.
type Node struct {
children map[rune]*Node // map children nodes
isLeaf bool // current node value
}
// NewNode creates a new Trie node with initialized
// children map.
func NewNode() *Node {
n := &Node{}
n.children = make(map[rune]*Node)
n.isLeaf = false
return n
}
// Insert inserts words at a Trie node.
func (n *Node) Insert(s string) {
curr := n
for _, c := range s {
next, ok := curr.children[c]
if !ok {
next = NewNode()
curr.children[c] = next
}
curr = next
}
curr.isLeaf = true
}
// Find finds words at a Trie node.
func (n *Node) Find(s string) bool {
curr := n
for _, c := range s {
next, ok := curr.children[c]
if !ok {
return false
}
curr = next
}
return true
}