-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrieData.go
More file actions
84 lines (67 loc) · 1.79 KB
/
Copy pathtrieData.go
File metadata and controls
84 lines (67 loc) · 1.79 KB
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
package main
import (
"fmt"
)
// A Trie is a tree structure and each node represent a word or a part of a word
// Path conected by the root can store words too
// An exemple of TrieData is the google searchbar, that tries to guess what you are trying to search
// Each node will have 26 children nodes
const AlphabetSize = 26
// Node Structure represents each node in the trie
// Each index of that array will hold a pointer to the chlild
type Node struct {
children [AlphabetSize]*Node
isEnd bool
}
// Trie Structure represent a trie and has a pointer to the root node
type Trie struct {
root *Node
}
// InitTrie will create a new Trie
func InitTrie() *Trie {
// Create a address variable
result := &Trie{root: &Node{}}
return result
}
// Insert will take in a word and add it to the trie
func (t *Trie) Insert(w string) {
wordLength := len(w)
currentNode := t.root
for i := 0; i < wordLength; i++ {
charIndex := w[i] - 'a'
if currentNode.children[charIndex] == nil {
currentNode.children[charIndex] = &Node{}
}
currentNode = currentNode.children[charIndex]
}
currentNode.isEnd = true
}
// Search will take in a word and return true is that word is included in the trie
func (t *Trie) Search(w string) bool {
wordLength := len(w)
currentNode := t.root
for i := 0; i < wordLength; i++ {
charIndex := w[i] - 'a'
if currentNode.children[charIndex] == nil {
return false
}
currentNode = currentNode.children[charIndex]
}
if currentNode.isEnd == true {
return true
}
return false
}
func main() {
myTrie := InitTrie()
toAdd := []string{
"rayani",
"melissa",
"daniel",
"lais",
}
for _, value := range toAdd {
myTrie.Insert(value)
}
fmt.Println(myTrie.Search("rayani"))
}