677.map-sum-pairs.go 968 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. type trie struct {
  2. freq int
  3. word bool
  4. next [26]*trie // '26' is quite important!
  5. }
  6. func (t *trie) insert(key string, val int) {
  7. res := t.search(key)
  8. if res != nil && res.word {
  9. val -= res.freq
  10. }
  11. for _, r := range key {
  12. i := r - 'a'
  13. if t.next[i] == nil {
  14. t.next[i] = &trie{}
  15. }
  16. t = t.next[i]
  17. t.freq += val
  18. }
  19. t.word = true
  20. }
  21. func (t *trie) search(key string) *trie {
  22. for _, r := range key {
  23. t = t.next[r-'a']
  24. if t == nil {
  25. break
  26. }
  27. }
  28. return t
  29. }
  30. type MapSum struct {
  31. tree trie
  32. }
  33. /** Initialize your data structure here. */
  34. func Constructor() MapSum {
  35. return MapSum{}
  36. }
  37. func (this *MapSum) Insert(key string, val int) {
  38. this.tree.insert(key, val)
  39. }
  40. func (this *MapSum) Sum(prefix string) int {
  41. res := this.tree.search(prefix)
  42. if res == nil {
  43. return 0
  44. }
  45. return res.freq
  46. }
  47. /**
  48. * Your MapSum object will be instantiated and called as such:
  49. * obj := Constructor();
  50. * obj.Insert(key,val);
  51. * param_2 := obj.Sum(prefix);
  52. */