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 来访问子节点。

以下是修正后的代码:

  1. type Trie struct {
  2. isEnd bool
  3. children [26]*Trie
  4. }
  5. func Constructor() Trie {
  6. return Trie{}
  7. }
  8. func (this *Trie) Insert(word string) {
  9. curNode := this
  10. for i := 0; i < len(word); i++ {
  11. index := word[i] - 'a'
  12. if curNode.children[index] == nil {
  13. curNode.children[index] = &Trie{}
  14. }
  15. curNode = curNode.children[index]
  16. }
  17. curNode.isEnd = true
  18. }
  19. func (this *Trie) Search(word string) bool {
  20. curNode := this
  21. for i := 0; i < len(word); i++ {
  22. index := word[i] - 'a'
  23. if curNode.children[index] == nil {
  24. return false
  25. }
  26. curNode = curNode.children[index]
  27. }
  28. return curNode.isEnd
  29. }
  30. func (this *Trie) StartsWith(prefix string) bool {
  31. curNode := this
  32. for i := 0; i < len(prefix); i++ {
  33. index := prefix[i] - 'a'
  34. if curNode.children[index] == nil {
  35. return false
  36. }
  37. curNode = curNode.children[index]
  38. }
  39. return true
  40. }
  41. /**
  42. * Your Trie object will be instantiated and called as such:
  43. * obj := Constructor();
  44. * obj.Insert(word);
  45. * param_2 := obj.Search(word);
  46. * param_3 := obj.StartsWith(prefix);
  47. */

修正的要点:

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

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?