力扣每日一题2021-11-14键值映射

leetcode每日一题 专栏收录该内容
178 篇文章 3 订阅

677.键值映射

思路：扫描、前缀树

扫描

Python实现

# 暴力扫描
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


Java实现

class MapSum {
Map<String, Integer> map;

public MapSum() {
map = new HashMap<>();
}

public void insert(String key, int val) {
map.put(key,val);
}

public int sum(String prefix) {
int res = 0;
for (String s: map.keySet()) {
if (s.startsWith(prefix)) {
res += map.get(s);
}
}
return res;
}
}


前缀树

Python实现

# 前缀树
class TrieNode:
def __init__(self):
self.val = 0
self.next = [None for _ in range(26)]

class MapSum:
def __init__(self):
self.root = TrieNode()
self.map = {}

def insert(self, key: str, val: int) -> None:
value = val
if key in self.map:
value -= self.map[key]
self.map[key] = val
node = self.root
for c in key:
if node.next[ord(c) - ord('a')] is None:
node.next[ord(c) - ord('a')] = TrieNode()
node = node.next[ord(c) - ord('a')]
node.val += value

def sum(self, prefix: str) -> int:
node = self.root
for c in prefix:
if node.next[ord(c) - ord('a')] is None:
return 0
node = node.next[ord(c) - ord('a')]
return node.val


Java实现

class MapSum {
class TrieNode {
int val = 0;
TrieNode[] next = new TrieNode[26];
}

TrieNode root;
Map<String, Integer> map;

public MapSum() {
root = new TrieNode();
map = new HashMap<>();
}

public void insert(String key, int val) {
int value = val - map.getOrDefault(key, 0);
map.put(key, val);
TrieNode node = root;
for (char c: key.toCharArray()) {
if (node.next[c - 'a'] == null) {
node.next[c - 'a'] = new TrieNode();
}
node = node.next[c - 'a'];
node.val += value;
}
}

public int sum(String prefix) {
TrieNode node = root;
for (char c: prefix.toCharArray()) {
if (node.next[c - 'a'] == null) {
return 0;
}
node = node.next[c - 'a'];
}
return node.val;
}
}

• 1
点赞
• 0
评论
• 0
收藏
• 打赏
• 扫一扫，分享海报

12-01 111
04-18 6214
04-17 2372

wcy1034036507

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。