设计一个 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
方法一:哈希表 + 前缀树
我们用哈希表
-
val
:以该节点为前缀的键值对的值的总和 -
children
:长度为$26$ 的数组,存放该节点的子节点
插入键值对 val
都要减去该键原来的值,然后再加上新的值。如果不存在,那么前缀树每个节点的 val
都要加上新的值。
查询前缀和时,我们从前缀树的根节点开始,遍历前缀字符串,如果当前节点的子节点中不存在该字符,那么说明前缀树中不存在该前缀,返回 val
。
时间复杂度方面,插入键值对的时间复杂度为
空间复杂度
class Trie:
def __init__(self):
self.children: List[Trie | None] = [None] * 26
self.val: int = 0
def insert(self, w: str, x: int):
node = self
for c in w:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.val += x
def search(self, w: str) -> int:
node = self
for c in w:
idx = ord(c) - ord('a')
if node.children[idx] is None:
return 0
node = node.children[idx]
return node.val
class MapSum:
def __init__(self):
self.d = defaultdict(int)
self.tree = Trie()
def insert(self, key: str, val: int) -> None:
x = val - self.d[key]
self.d[key] = val
self.tree.insert(key, x)
def sum(self, prefix: str) -> int:
return self.tree.search(prefix)
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)
class Trie {
private Trie[] children = new Trie[26];
private int val;
public void insert(String w, int x) {
Trie node = this;
for (int i = 0; i < w.length(); ++i) {
int idx = w.charAt(i) - 'a';
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
node.val += x;
}
}
public int search(String w) {
Trie node = this;
for (int i = 0; i < w.length(); ++i) {
int idx = w.charAt(i) - 'a';
if (node.children[idx] == null) {
return 0;
}
node = node.children[idx];
}
return node.val;
}
}
class MapSum {
private Map<String, Integer> d = new HashMap<>();
private Trie trie = new Trie();
public MapSum() {
}
public void insert(String key, int val) {
int x = val - d.getOrDefault(key, 0);
d.put(key, val);
trie.insert(key, x);
}
public int sum(String prefix) {
return trie.search(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 Trie {
public:
Trie()
: children(26, nullptr) {
}
void insert(string& w, int x) {
Trie* node = this;
for (char c : w) {
c -= 'a';
if (!node->children[c]) {
node->children[c] = new Trie();
}
node = node->children[c];
node->val += x;
}
}
int search(string& w) {
Trie* node = this;
for (char c : w) {
c -= 'a';
if (!node->children[c]) {
return 0;
}
node = node->children[c];
}
return node->val;
}
private:
vector<Trie*> children;
int val = 0;
};
class MapSum {
public:
MapSum() {
}
void insert(string key, int val) {
int x = val - d[key];
d[key] = val;
trie->insert(key, x);
}
int sum(string prefix) {
return trie->search(prefix);
}
private:
unordered_map<string, int> d;
Trie* trie = new Trie();
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/
type trie struct {
children [26]*trie
val int
}
func (t *trie) insert(w string, x int) {
for _, c := range w {
c -= 'a'
if t.children[c] == nil {
t.children[c] = &trie{}
}
t = t.children[c]
t.val += x
}
}
func (t *trie) search(w string) int {
for _, c := range w {
c -= 'a'
if t.children[c] == nil {
return 0
}
t = t.children[c]
}
return t.val
}
type MapSum struct {
d map[string]int
t *trie
}
func Constructor() MapSum {
return MapSum{make(map[string]int), &trie{}}
}
func (this *MapSum) Insert(key string, val int) {
x := val - this.d[key]
this.d[key] = val
this.t.insert(key, x)
}
func (this *MapSum) Sum(prefix string) int {
return this.t.search(prefix)
}
/**
* Your MapSum object will be instantiated and called as such:
* obj := Constructor();
* obj.Insert(key,val);
* param_2 := obj.Sum(prefix);
*/
class Trie {
children: Trie[];
val: number;
constructor() {
this.children = new Array(26);
this.val = 0;
}
insert(w: string, x: number) {
let node: Trie = this;
for (const c of w) {
const i = c.charCodeAt(0) - 97;
if (!node.children[i]) {
node.children[i] = new Trie();
}
node = node.children[i];
node.val += x;
}
}
search(w: string): number {
let node: Trie = this;
for (const c of w) {
const i = c.charCodeAt(0) - 97;
if (!node.children[i]) {
return 0;
}
node = node.children[i];
}
return node.val;
}
}
class MapSum {
d: Map<string, number>;
t: Trie;
constructor() {
this.d = new Map();
this.t = new Trie();
}
insert(key: string, val: number): void {
const x = val - (this.d.get(key) ?? 0);
this.d.set(key, val);
this.t.insert(key, x);
}
sum(prefix: string): number {
return this.t.search(prefix);
}
}
/**
* Your MapSum object will be instantiated and called as such:
* var obj = new MapSum()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/