Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
-
Trie()
初始化前缀树对象。 -
void insert(String word)
向前缀树中插入字符串word
。 -
boolean search(String word)
如果字符串word
在前缀树中,返回true
(即,在检索之前已经插入);否则,返回false
。 -
boolean startsWith(String prefix)
如果之前已经插入的字符串word
的前缀之一为prefix
,返回true
;否则,返回false
。
type Trie struct {
isEnd bool //是否为一个单词的结束
next [26]*Trie //保存下一个字符的26种可能;next数组保存了当前字符的下一个字符节点数组
}
/** Initialize your data structure here. */
func Constructor() Trie {
return Trie{}
}
/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
node := this
//遍历单词的每个字符,判断字符所在的索引位置是否有值,有值则继续遍历,没有则创建一个新的节点
for _, char := range word {
index = char - 'a'
if node.next[index] == nil {
node.next[index] = &Trie{}
}
node = node.next[index]
}
node.isEnd = true //遍历到最后设置为true
}
/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
node := this
for _, char := range word {
index = char - 'a'
if node.next[index] == nil {
node.next[index] = &Trie{}
}
node = node.next[index]
}
return node.isEnd
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
node := this
for _, char := range prefix {
char = char - 'a'
if node.next[char] == nil {
return false
}
node = node.next[char]
}
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);
*/