type Trie struct {
subChar []*Trie
end bool
}
func Constructor() Trie {
return Trie{
subChar: make([]*Trie, 26),
}
}
func (this *Trie) Insert(word string) {
node := this
for _, char := range word {
idx := char - 'a'
if node.subChar[idx] == nil {
sub := Constructor()
node.subChar[idx] = &sub
}
node = node.subChar[idx]
}
node.end = true
}
func (this *Trie) search(word string) *Trie {
node := this
for _, char := range word {
idx := char - 'a'
if node.subChar[idx] == nil {
return nil
}
node = node.subChar[idx]
}
return node
}
func (this *Trie) Search(word string) bool {
node := this.search(word)
if node == nil || !node.end {
return false
}
return true
}
func (this *Trie) StartsWith(prefix string) bool {
return this.search(prefix) != nil
}