你的代码有一些小错误。具体来说,在 Insert
方法中,你在更新当前节点时使用了错误的指针,导致它无法正确插入新单词。此外,在遍历字符数组时应该使用 curNode
而不是 this
来访问子节点。
以下是修正后的代码:
type Trie struct {
isEnd bool
children [26]*Trie
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) Insert(word string) {
curNode := this
for i := 0; i < len(word); i++ {
index := word[i] - 'a'
if curNode.children[index] == nil {
curNode.children[index] = &Trie{}
}
curNode = curNode.children[index]
}
curNode.isEnd = true
}
func (this *Trie) Search(word string) bool {
curNode := this
for i := 0; i < len(word); i++ {
index := word[i] - 'a'
if curNode.children[index] == nil {
return false
}
curNode = curNode.children[index]
}
return curNode.isEnd
}
func (this *Trie) StartsWith(prefix string) bool {
curNode := this
for i := 0; i < len(prefix); i++ {
index := prefix[i] - 'a'
if curNode.children[index] == nil {
return false
}
curNode = curNode.children[index]
}
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);
*/
修正的要点:
- 在
Insert
,Search
, 和StartsWith
函数中,我确保在计算索引时总是使用curNode
,而不是原来的this
。 - 在条件检查中,索引计算只需要进行一次,并将其存储在一个变量中以避免重复计算,这样会使代码更清晰。
这个实现现在应该可以正常工作。如果还有其他问题,请告诉我!
内容由零声教学AI助手提供,问题来源于学员提问