class MapSum {
public:
MapSum() {
}
void insert(string key, int val) {
}
int sum(string prefix) {
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/
'''
暴力扫描
'''
class MapSum:
def __init__(self):
self.map = {}
def insert(self, key: str, val: int) -> None:
self.map[key] = val
def sum(self, prefix: str) -> int:
res = 0
for key,val in self.map.items():
if key.startswith(prefix):
res += val
return res
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)
class MapSum:
def __init__(self):
self.map = {}
self.prefixmap = {}
def insert(self, key: str, val: int) -> None:
delta = val
if key in self.map:
delta -= self.map[key]
self.map[key] = val
for i in range(len(key)):
currprefix = key[0:i+1]
if currprefix in self.prefixmap:
self.prefixmap[currprefix] += delta
else:
self.prefixmap[currprefix] = delta
def sum(self, prefix: str) -> int:
if prefix in self.prefixmap:
return self.prefixmap[prefix]
else:
return 0
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)