-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap-sum-pairs.py
48 lines (36 loc) · 1.12 KB
/
map-sum-pairs.py
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
class TrieNode:
def __init__(self,val):
self.children = {}
self.val = val
# self.is_end
class MapSum:
def __init__(self):
self.root = TrieNode(0)
self.map = {}
def insert(self, key: str, val: int) -> None:
cur = self.root
if key in self.map:
for ch in key:
cur.children[ch].val += ( - self.map[key] + val)
cur = cur.children[ch]
else:
for ch in key:
if ch not in cur.children:
cur.children[ch] = TrieNode(val)
else:
cur.children[ch].val += val
cur = cur.children[ch]
# cur.is_end = True
self.map[key] = val
def sum(self, prefix: str) -> int:
cur = self.root
for ch in prefix:
if ch in cur.children:
cur = cur.children[ch]
else:
return 0
return cur.val
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)