(18)Go實(shí)現(xiàn)的trie解答leetcode-677

用數(shù)組trie解決
type MapSum struct {
    value int
    next  [26]*MapSum
}

func Constructor() MapSum {
    return MapSum{}
}

func (this *MapSum) Insert(key string, val int) {
    if len(key) == 0 {
        return
    }

    for _, v := range key {
        if this.next[v-97] == nil {
            this.next[v-97] = new(MapSum)
        }
        this = this.next[v-97]
    }
    this.value = val
}

func (this *MapSum) Sum(prefix string) int {
    length := len(prefix)
    if length == 0 {
        return 0
    }

    for i := 0; i < length; i++ {
        if this = this.next[prefix[i]-97]; this == nil {
            return 0
        }
    }
    return this.sumResp()
}

// 求該節(jié)點(diǎn)和該節(jié)點(diǎn)所有子節(jié)點(diǎn)的value的總和
unc (this *MapSum) sumResp() int {
    resp := this.value
    for i := 0; i < 26; i++ {
        if this.next[i] == nil {
            continue
        }
        resp = resp + this.next[i].sumResp()
    }
    return resp
}
測(cè)試通過(guò)

相關(guān):
1)trie解決leetcode-207:實(shí)現(xiàn)trie
http://www.lxweimin.com/p/d95153f382f6
2)trie解決leetcode-211:添加與搜索單詞
http://www.lxweimin.com/p/74103f51aa36

有bug歡迎指出,轉(zhuǎn)載請(qǐng)注明出處。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。