Skip to content

Instantly share code, notes, and snippets.

@vxcute
Created February 13, 2023 21:38
Show Gist options
  • Save vxcute/3662835dad493e676f088cbbf26b2079 to your computer and use it in GitHub Desktop.
Save vxcute/3662835dad493e676f088cbbf26b2079 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
const CharsNum = 256
type TrieNode struct {
children [CharsNum] *TrieNode
isEnd bool
wordcount int
}
func NewTrieNode() *TrieNode {
return &TrieNode{}
}
func (t *TrieNode) Insert(s string) {
currentNode := t
for i := range s {
if currentNode.children[s[i]] == nil {
currentNode.children[s[i]] = NewTrieNode()
}
currentNode = currentNode.children[s[i]]
}
currentNode.isEnd = true
t.wordcount++
}
func (t *TrieNode) Search(s string) bool {
currentNode := t
for i := range s {
if currentNode.children[s[i]] == nil {
return false
}
currentNode = currentNode.children[s[i]]
}
return currentNode.isEnd
}
func (t *TrieNode) Print() {
str := make([]rune, 20)
print(t, str, 0)
}
func (t *TrieNode) Count() int {
return t.wordcount
}
func print(t *TrieNode, str []rune, len int) {
if t.isEnd {
fmt.Println(string(str))
}
for i := 0; i < CharsNum; i++ {
if t.children[i] != nil {
str[len] = rune(i)
print(t.children[i], str, len + 1)
}
}
}
func main() {
trie := NewTrieNode()
trie.Insert("Rake")
trie.Insert("FUCK")
fmt.Println(trie.Search("Ahmed"))
trie.Print()
fmt.Println(trie.Count())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment