用數(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)注明出處。