提供一个go版本
type Trie struct {
children map[rune]*Trie
isEnd bool
}
func Constructor() *Trie {
return &Trie{map[rune]*Trie{}, false}
}
func (t *Trie) Insert(word string) {
node := t
for _, char := range word {
nextNode, ok := node.children[char]
if !ok {
nextNode = Constructor()
node.children[char] = nextNode
}
node = nextNode
}
node.isEnd = true
}
func (t *Trie) Search(word string) bool {
node := t
for _, char := range word {
nextNode, ok := node.children[char]
if !ok {
return false
}
node = nextNode
}
return node.isEnd
}
func (t *Trie) StartWith(prefix string) bool {
node := t
for _, char := range prefix {
nextNode, ok := node.children[char]
if !ok {
return false
}
node = nextNode
}
return true
}
展开