-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path677_map_sum_pairs.rb
53 lines (44 loc) · 945 Bytes
/
677_map_sum_pairs.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# frozen_string_literal: true
# https://leetcode.com/problems/map-sum-pairs/
class MapSum
# Init
def initialize
@root = ::MapSum::Node.new
@values = {}
end
# @param {String} key
# @param {Integer} val
# @return {Void}
def insert(key, val)
delta = val - @values.fetch(key, 0)
@values[key] = val
curr = @root
curr.score += delta
(0...key.size).each do |i|
c = key[i]
curr.children[c] = ::MapSum::Node.new unless curr.children.key?(c)
curr = curr.children[c]
curr.score += delta
end
end
# @param {String} prefix
# @return {Integer}
def sum(prefix)
curr = @root
(0...prefix.size).each do |i|
c = prefix[i]
curr = curr.children[c]
return 0 unless curr
end
curr.score
end
# Node realization
class Node
attr_accessor :children, :score
# Init
def initialize
@children = {}
@score = 0
end
end
end