Last active
March 11, 2022 15:50
-
-
Save johnnyeric/110893a0f2c344b67be3e417d55c6cad to your computer and use it in GitHub Desktop.
Simple Trie implementation in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package trie | |
type Node struct { | |
Children [26]*Node | |
Char rune | |
IsRoot bool | |
IsWordEnd bool | |
} | |
type Trie struct { | |
Root *Node | |
} | |
func NewTrie() *Trie { | |
return &Trie{ | |
Root: &Node{ | |
IsRoot: true, | |
}, | |
} | |
} | |
func (t *Trie) AddWord(word string) { | |
curr := t.Root | |
for _, char := range word { | |
idx := char - 'a' | |
if curr.Children[idx] == nil { | |
curr.Children[idx] = &Node{ | |
IsRoot: false, | |
Char: char, | |
} | |
} | |
curr = curr.Children[idx] | |
} | |
curr.IsWordEnd = true | |
} | |
func (t *Trie) Find(word string) bool { | |
curr := t.findNode(word) | |
return curr.IsWordEnd | |
} | |
func (t *Trie) findNode(word string) *Node { | |
curr := t.Root | |
for _, char := range word { | |
if char < 97 || char > 122 { | |
continue | |
} | |
idx := char - 'a' | |
if curr.Children[idx] == nil { | |
return nil | |
} | |
curr = curr.Children[idx] | |
} | |
return curr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment