题目

类型:design

image.png

解题思路

字典树
由于要处理前缀,自然而然联想到可以用 Trie(前缀树)来处理此问题。
在前缀对应的 Trie 的每个节点存储该前缀对应的值。

  • insert 操作:首先求出前缀对应的值的改变 delta,直接在 Trie 节点上更新键 key 的每个前缀对应的值。
  • sum 操作:直接在前缀树上搜索该给定的前缀对应的值即可,如果给定的前缀不在前缀树中,则返回 0。

当然在实际中也可以在 Trie 的节点只存储键 key 对应的 val, 每次求 sum 时利用 DFS 或者 BFS 遍历前缀树的子树即可。

代码

  1. class MapSum {
  2. class TrieNode {
  3. int val = 0;
  4. TrieNode[] next = new TrieNode[26];
  5. }
  6. TrieNode root;
  7. Map<String, Integer> map;
  8. public MapSum() {
  9. root = new TrieNode();
  10. map = new HashMap<>();
  11. }
  12. public void insert(String key, int val) {
  13. int delta = val - map.getOrDefault(key, 0);
  14. map.put(key, val);
  15. TrieNode node = root;
  16. for (char c : key.toCharArray()) {
  17. if (node.next[c - 'a'] == null) {
  18. node.next[c - 'a'] = new TrieNode();
  19. }
  20. node = node.next[c - 'a'];
  21. node.val += delta;
  22. }
  23. }
  24. public int sum(String prefix) {
  25. TrieNode node = root;
  26. for (char c : prefix.toCharArray()) {
  27. if (node.next[c - 'a'] == null) {
  28. return 0;
  29. }
  30. node = node.next[c - 'a'];
  31. }
  32. return node.val;
  33. }
  34. }