class MapSum {
public:
/** Initialize your data structure here. */
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 = {}
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)
// 前缀哈希映射
type MapSum struct {
m, pre map[string]int
}
func Constructor() MapSum {
return MapSum{map[string]int{}, map[string]int{}}
}
func (m *MapSum) Insert(key string, val int) {
delta := val
if m.m[key] > 0 {
delta -= m.m[key]
}
m.m[key] = val
for i := range key {
m.pre[key[:i+1]] += delta
}
}
func (m *MapSum) Sum(prefix string) int {
return m.pre[prefix]
}
/**
* Your MapSum object will be instantiated and called as such:
* obj := Constructor();
* obj.Insert(key,val);
* param_2 := obj.Sum(prefix);
*/
type MapSum map[string]int
func Constructor() MapSum {
return MapSum{}
}
func (m MapSum) Insert(key string, val int) {
m[key] = val
}
func (m MapSum) Sum(prefix string) (sum int) {
for s, v := range m {
if strings.HasPrefix(s, prefix) {
sum += v
}
}
return
}
/**
* Your MapSum object will be instantiated and called as such:
* obj := Constructor();
* obj.Insert(key,val);
* 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)