dongshan2680 2016-03-08 08:30
浏览 28

使用地图进行Trie实现

I am trying to implement the Trie data structure using go but I am not that familiar with the language nor using a map and was wondering if there were some tips to how I can factor out some of my recursion so it doesn't look so bad. Also would appreciate it if I could get some help on how to make just the add method better (less lines of code).

Just noticed the problem where the tree itself would never know when a word is added so definitely a solution to that would be great!

// The overall tree
type TrieTree struct { 
    root TrieNode
    count int
}

// The node for each character inside the tree
type TrieNode struct {
    letter string // this is the value of the current node 
    isWord bool // if this letter + all of its parents make a word set = to true 
    children map[string]*TrieNode // maps children nodes
}

//method for adding a word into the tree
func (root *TrieNode, entry string) AddEntry() {
    //in case someone is trying to mess you up
    if (entry != nil || len(entry) != 0 || root != nil) {
        entry = strings.ToLower(entry)
        AddEntryHelper(root, entry, 0)
    }
}

func (node *TrieNode, entry string, count int) AddEntryHelper() {
    // the last one and no child yet
    if(node.children == nil && count == len(entry)-1) { 
        node.children=(map[string(entry[count])]=TrieNode{string(entry[count]), true, nil})
    // no children and not last one
    } else if(node.children == nil && count != len(entry)-1) { 
        node.children=(map[string(entry[count])]=TrieNode{string(entry[count]), false, nil})
        AddEntryHelper(node.children[string(entry[count])], entry, count++) 
    // last one and child exist
    } else if (node.children != nil && count == len(entry)-1) {
        node.children[string(entry[count])].isWord = true
    // children node exists and just need to recurse down
    } else {
        AddEntryHelper(node.children[string(entry[count])], entry, count++)
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?