Skip to content

Commit 358cd20

Browse files
authored
Go/trie
2 parents e8e5b58 + 3e44769 commit 358cd20

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Go/Data-Structures/trie/main.go

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package main
2+
3+
import "fmt"
4+
5+
// AlphabetSize is the number of possible characters in the trie
6+
const AlphabetSize = 26
7+
8+
// Node represents each node in the trie
9+
type Node struct {
10+
children [26]*Node
11+
isEnd bool
12+
}
13+
14+
// Trie represenst a trie and has a pointer to the root node
15+
type Trie struct {
16+
root *Node
17+
}
18+
19+
// InitTrie will create new Trie
20+
func InitTrie() *Trie {
21+
result := &Trie{root: &Node{}}
22+
return result
23+
}
24+
25+
// Insert will take in a word and add it to the trie
26+
func (t *Trie) Insert(w string) {
27+
wordLength := len(w)
28+
currentNode := t.root
29+
for i := 0; i < wordLength; i++ {
30+
charIndex := w[i] - 'a'
31+
if currentNode.children[charIndex] == nil {
32+
currentNode.children[charIndex] = &Node{}
33+
}
34+
currentNode = currentNode.children[charIndex]
35+
}
36+
currentNode.isEnd = true
37+
}
38+
39+
// Search will take in a word and RETURN true is that word is included in the trie
40+
func (t *Trie) Search(w string) bool {
41+
wordLength := len(w)
42+
currentNode := t.root
43+
for i := 0; i < wordLength; i++ {
44+
charIndex := w[i] - 'a'
45+
if currentNode.children[charIndex] == nil {
46+
return false
47+
}
48+
currentNode = currentNode.children[charIndex]
49+
}
50+
if currentNode.isEnd == true {
51+
return true
52+
}
53+
54+
return false
55+
}
56+
57+
func main() {
58+
myTrie := InitTrie()
59+
60+
toAdd := []string{
61+
"aragorn",
62+
"aragon",
63+
"argon",
64+
"eragon",
65+
"oregon",
66+
"oregano",
67+
"oreo",
68+
}
69+
70+
for _, v := range toAdd {
71+
myTrie.Insert(v)
72+
}
73+
74+
fmt.Println(myTrie.Search("wizard"))
75+
}

0 commit comments

Comments
 (0)