A Trie (pronounced as "try") is a specialized tree-like data structure that is primarily used to store associative data, typically strings. It is particularly useful for tasks such as autocomplete and spell-checking since it enables efficient retrieval of keys based on prefixes.
Below is an example of how you can implement a simple Trie in Go:
package main
import (
"fmt"
)
type TrieNode struct {
children map[rune]*TrieNode
isEnd bool
}
type Trie struct {
root *TrieNode
}
func NewTrie() *Trie {
return &Trie{root: &TrieNode{children: make(map[rune]*TrieNode)}}
}
func (t *Trie) Insert(word string) {
node := t.root
for _, char := range word {
if _, exists := node.children[char]; !exists {
node.children[char] = &TrieNode{children: make(map[rune]*TrieNode)}
}
node = node.children[char]
}
node.isEnd = true
}
func (t *Trie) Search(word string) bool {
node := t.root
for _, char := range word {
if _, exists := node.children[char]; !exists {
return false
}
node = node.children[char]
}
return node.isEnd
}
func main() {
trie := NewTrie()
trie.Insert("hello")
fmt.Println(trie.Search("hello")) // true
fmt.Println(trie.Search("hell")) // false
}
`.
- The example of the Trie implementation in Go is enclosed in a `` block with the specified class.
- Keywords are specified in the ``.
- A brief description is included in the ``.
Feel free to modify the content as needed!
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?