677. Map Sum Pairs Medium

@problem@discussion
#Hash Table#String#Design#Trie



1/**
2 * [677] Map Sum Pairs
3 *
4 * Design a map that allows you to do the following:
5 * 
6 * 	Maps a string key to a given value.
7 * 	Returns the sum of the values that have a key with a prefix equal to a given string.
8 * 
9 * Implement the MapSum class:
10 * 
11 * 	MapSum() Initializes the MapSum object.
12 * 	void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
13 * 	int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.
14 * 
15 *  
16 * Example 1:
17 * 
18 * Input
19 * ["MapSum", "insert", "sum", "insert", "sum"]
20 * [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
21 * Output
22 * [null, null, 3, null, 5]
23 * Explanation
24 * MapSum mapSum = new MapSum();
25 * mapSum.insert("apple", 3);  
26 * mapSum.sum("ap");           // return 3 (<u>ap</u>ple = 3)
27 * mapSum.insert("app", 2);    
28 * mapSum.sum("ap");           // return 5 (<u>ap</u>ple + <u>ap</u>p = 3 + 2 = 5)
29 * 
30 *  
31 * Constraints:
32 * 
33 * 	1 <= key.length, prefix.length <= 50
34 * 	key and prefix consist of only lowercase English letters.
35 * 	1 <= val <= 1000
36 * 	At most 50 calls will be made to insert and sum.
37 * 
38 */
39pub struct Solution {}
40
41// problem: https://leetcode.com/problems/map-sum-pairs/
42// discuss: https://leetcode.com/problems/map-sum-pairs/discuss/?currentPage=1&orderBy=most_votes&query=
43
44// submission codes start here
45
46struct MapSum {
47        false
48    }
49
50
51/** 
52 * `&self` means the method takes an immutable reference.
53 * If you need a mutable reference, change it to `&mut self` instead.
54 */
55impl MapSum {
56
57    fn new() -> Self {
58        
59    }
60    
61    fn insert(&self, key: String, val: i32) {
62        
63    }
64    
65    fn sum(&self, prefix: String) -> i32 {
66        
67    }
68}
69
70/**
71 * Your MapSum object will be instantiated and called as such:
72 * let obj = MapSum::new();
73 * obj.insert(key, val);
74 * let ret_2: i32 = obj.sum(prefix);
75 */
76
77// submission codes end
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn test_677() {
85    }
86}
87


Back
© 2025 bowen.ge All Rights Reserved.