Skip to content

Commit

Permalink
Create Go Solution for 208-Implement-Trie
Browse files Browse the repository at this point in the history
  • Loading branch information
maxts0gt committed Sep 1, 2022
1 parent b25d73e commit e658713
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions go/208-Implement-Trie.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
type Trie struct {
children [26]*Trie
endOfWord bool
root *Trie
}

func Constructor() Trie {
return Trie{
children: [26]*Trie{},
endOfWord: false,
root: &Trie{}}
}

func (this *Trie) Insert(word string) {
cur := this.root

for i := 0; i < len(word); i++ {
index := word[i] - 'a'
if cur.children[index] == nil {
cur.children[index] = &Trie{}
}
cur = cur.children[index]
}

cur.endOfWord = true
}

func (this *Trie) Search(word string) bool {
cur := this.root

for i := 0; i < len(word); i++ {
index := word[i] - 'a'
if cur.children[index] == nil {
return false
}
cur = cur.children[index]
}

return cur.endOfWord
}

func (this *Trie) StartsWith(prefix string) bool {
cur := this.root

for i := 0; i < len(prefix); i++ {
index := prefix[i] - 'a'
if cur.children[index] == nil {
return false
}
cur = cur.children[index]
}

return true
}

0 comments on commit e658713

Please sign in to comment.