677. 键值映射
设计一个 map ,满足以下几点:
- 字符串表示键,整数表示值
- 返回具有前缀等于给定字符串的键的值的总和
实现一个
MapSum
类:MapSum()
初始化MapSum
对象
void insert(String key, int val)
插入key-val
键值对,字符串表示键key
,整数表示值val
。如果键key
已经存在,那么原来的键值对key-value
将被替代成新的键值对。
int sum(string prefix)
返回所有以该前缀prefix
开头的键key
的值的总和。
示例 1:
输入: ["MapSum", "insert", "sum", "insert", "sum"] [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] 输出: [null, null, 3, null, 5] 解释: MapSum mapSum = new MapSum(); mapSum.insert("apple", 3); mapSum.sum("ap"); // 返回 3 (apple = 3) mapSum.insert("app", 2); mapSum.sum("ap"); // 返回 5 (apple +app = 3 + 2 = 5)
提示:
1 <= key.length, prefix.length <= 50
key
和prefix
仅由小写英文字母组成
1 <= val <= 1000
- 最多调用
50
次insert
和sum
通过次数39,954提交次数60,108
字典树
思路
详见代码
题解
class Node: def __init__(self): self.child = {} self.num = 0 class TrieTree: def __init__(self): self.root = Node() def add(self, word, val): node = self.root for char in word: if char not in node.child: node.child[char] = Node() node = node.child[char] node.num = val def search_prefix(self, prefix): # 返回 最后一个字母的节点 node = self.root res = 0 for char in prefix: if char not in node.child: return False node = node.child[char] return node class MapSum: def __init__(self): self.t = TrieTree() def insert(self, key: str, val: int) -> None: self.t.add(key, val) def sum(self, prefix: str) -> int: node = self.t.search_prefix(prefix) if node is False: return 0 return self.helper(node) def helper(self, node): # 将该节点以下的值均相加(包括该节点的) res = node.num for _, nxt in node.child.items(): res += self.helper(nxt) return res # Your MapSum object will be instantiated and called as such: # obj = MapSum() # obj.insert(key,val) # param_2 = obj.sum(prefix)