ZBLOG

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++ { if this.children[word[i] - 'a'] ...

你的代码有一些小错误。具体来说,在 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);
 */

修正的要点:

  1. Insert, Search, 和 StartsWith 函数中,我确保在计算索引时总是使用 curNode,而不是原来的 this
  2. 在条件检查中,索引计算只需要进行一次,并将其存储在一个变量中以避免重复计算,这样会使代码更清晰。

这个实现现在应该可以正常工作。如果还有其他问题,请告诉我!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=19258

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?