Last active
September 24, 2017 00:22
-
-
Save cixuuz/70a2980666c1338334f199784a67faa5 to your computer and use it in GitHub Desktop.
[677. Map Sum Pairs] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class MapSum { | |
| class TrieNode { | |
| int val; | |
| Map<Character, TrieNode> next; | |
| boolean isWord; | |
| public TrieNode() { | |
| val = 0; | |
| next = new HashMap<Character, TrieNode>(); | |
| isWord = false; | |
| } | |
| } | |
| /** Initialize your data structure here. */ | |
| TrieNode root; | |
| public MapSum() { | |
| root = new TrieNode(); | |
| } | |
| public void insert(String key, int val) { | |
| TrieNode node = root; | |
| for (char c : key.toCharArray()) { | |
| if (!node.next.containsKey(c)) { | |
| TrieNode child = new TrieNode(); | |
| node.next.put(c, child); | |
| } | |
| node = node.next.get(c); | |
| } | |
| node.val = val; | |
| } | |
| public int sum(String prefix) { | |
| TrieNode node = root; | |
| for (char c : prefix.toCharArray()) { | |
| if (!node.next.containsKey(c)) { | |
| return 0; | |
| } | |
| node = node.next.get(c); | |
| } | |
| return dfs(node); | |
| } | |
| private int dfs(TrieNode root) { | |
| int sum = 0; | |
| for (char c : root.next.keySet()) { | |
| sum += dfs(root.next.get(c)); | |
| } | |
| return sum + root.val; | |
| } | |
| } | |
| /** | |
| * 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 { | |
| Map<String, Integer> map; | |
| Map<String, Integer> original; | |
| /** Initialize your data structure here. */ | |
| public MapSum() { | |
| map = new HashMap<>(); | |
| original = new HashMap<>(); | |
| } | |
| public void insert(String key, int val) { | |
| int diff = val - original.getOrDefault(key, 0); | |
| String s = ""; | |
| map.put(s, map.getOrDefault(s, 0) + diff); | |
| for (char c : key.toCharArray()) { | |
| s += c; | |
| map.put(s, map.getOrDefault(s, 0) + diff); | |
| } | |
| original.put(key, original.getOrDefault(key, 0) + diff); | |
| } | |
| public int sum(String prefix) { | |
| return map.getOrDefault(prefix, 0); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment