📑 题目:208. 实现 Trie (前缀树)
中等 🕓 2021-09-08 📈 频次: 15
**
题目大意
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
解题思路
- 要求实现一个 Trie 的数据结构,具有
insert
,search
,startsWith
三种操作 - 这一题就是经典的 Trie 实现。本题的实现可以作为 Trie 的模板。
代码
package leetcode
type Trie struct {
isWord bool
children map[rune]*Trie
}
/** Initialize your data structure here. */
func Constructor208() Trie {
return Trie{isWord: false, children: make(map[rune]*Trie)}
}
/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
parent := this
for _, ch := range word {
if child, ok := parent.children[ch]; ok {
parent = child
} else {
newChild := &Trie{children: make(map[rune]*Trie)}
parent.children[ch] = newChild
parent = newChild
}
}
parent.isWord = true
}
/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
parent := this
for _, ch := range word {
if child, ok := parent.children[ch]; ok {
parent = child
continue
}
return false
}
return parent.isWord
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
parent := this
for _, ch := range prefix {
if child, ok := parent.children[ch]; ok {
parent = child
continue
}
return false
}
return true
}
/**
* Your Trie object will be instantiated and called as such:
* obj := Constructor();
* obj.Insert(word);
* param_2 := obj.Search(word);
* param_3 := obj.StartsWith(prefix);
*/