Class MapSum

java.lang.Object
g0601_0700.s0677_map_sum_pairs.MapSum

public class MapSum extends Object
677 - Map Sum Pairs.<p>Medium</p> <p>Design a map that allows you to do the following:</p> <ul> <li>Maps a string key to a given value.</li> <li>Returns the sum of the values that have a key with a prefix equal to a given string.</li> </ul> <p>Implement the <code>MapSum</code> class:</p> <ul> <li><code>MapSum()</code> Initializes the <code>MapSum</code> object.</li> <li><code>void insert(String key, int val)</code> Inserts the <code>key-val</code> pair into the map. If the <code>key</code> already existed, the original <code>key-value</code> pair will be overridden to the new one.</li> <li><code>int sum(string prefix)</code> Returns the sum of all the pairs&rsquo; value whose <code>key</code> starts with the <code>prefix</code>.</li> </ul> <p><strong>Example 1:</strong></p> <p><strong>Input</strong></p> <p>[&ldquo;MapSum&rdquo;, &ldquo;insert&rdquo;, &ldquo;sum&rdquo;, &ldquo;insert&rdquo;, &ldquo;sum&rdquo;] [ [],</p> <p>[&ldquo;apple&rdquo;, 3], [&ldquo;ap&rdquo;], [&ldquo;app&rdquo;, 2], [&ldquo;ap&rdquo;]]</p> <p><strong>Output:</strong> [null, null, 3, null, 5]</p> <p><strong>Explanation:</strong></p> <pre><code> MapSum mapSum = new MapSum(); mapSum.insert(&quot;apple&quot;, 3); mapSum.sum(&quot;ap&quot;); // return 3 (apple = 3) mapSum.insert(&quot;app&quot;, 2); mapSum.sum(&quot;ap&quot;); // return 5 (apple + app = 3 + 2 = 5) </code></pre> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= key.length, prefix.length <= 50</code></li> <li><code>key</code> and <code>prefix</code> consist of only lowercase English letters.</li> <li><code>1 <= val <= 1000</code></li> <li>At most <code>50</code> calls will be made to <code>insert</code> and <code>sum</code>.</li> </ul>
  • Constructor Details

    • MapSum

      public MapSum()
  • Method Details

    • insert

      public void insert(String key, int val)
    • sum

      public int sum(String prefix)