← 筆記

[LeetCode刷題筆記] 677 - Map Sum Pairs

題目描述:

Implement the MapSum class:

  • MapSum() Initializes the MapSum object.
  • 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.
  • int sum(string prefix) Returns the sum of all the pairs’ value whose key starts with the prefix.

Example 1:

Input
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output
[null, null, 3, null, 5]

Explanation
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);  
mapSum.sum("ap");           // return 3 (apple = 3)
mapSum.insert("app", 2);    
mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)

Constraints:

  • 1 <= key.length, prefix.length <= 50
  • key and prefix consist of only lowercase English letters.
  • 1 <= val <= 1000
  • At most 50 calls will be made to insert and sum.

一刷題解(Trie):

這題需要我們去寫一個MapSum的類,這個類需要我們實現一個插入方法,將一個string:int的鍵值對放進數據結構裡;另外實現一個加總的方法,通過傳入一個string,檢查數據結構裡以這個string為前綴的所有鍵,並將它們的總和加總起來。

第一感覺是用字典去做,畢竟有鍵值對這個元素。但是試著用字典後發現不太好做,因為除了插入鍵值對以外,還需要檢查字符串的前綴,進行前綴的檢查最好還是使用Trie(字首樹)來做比較好。

使用字首樹來做,首先要有一個字首樹節點的類,這個類裡要有一個包含26個子母子節點的數組,一個int值記錄insert傳進來的val。在Insert時,按照字首樹的一般遍歷方法,遍歷字符串中的所有字符,最後把值賦給字符串終點的字符節點中。

進行加總時,同樣是將傳進來的prefix從頭遍歷到尾部,確定有這個prefix的存在。然後再對這個prefix下的所有字母節點進行深度優先查找,得到所有以這個prefix為前綴的子節點的值,最後進行加總,得出結果。

public class MapSum {

    MapSumNode root;
    
    /** Initialize your data structure here. */
    public MapSum() {
        root = new MapSumNode();
    }
    
    //插入元素
    public void Insert(string key, int val) {
        MapSumNode curr = root;
        for(int i = 0; i < key.Length; i++)
        {
            int id = key[i] - 'a';
            if(curr.children[id] == null)
            {
                curr.children[id] = new MapSumNode();
            }
            curr = curr.children[id];
        }
        curr.val = val;
    }
    
    public int Sum(string prefix) {
        MapSumNode curr = root;
        //需要遍歷到prefix的尾部以確認prefix的存在
        for(int i = 0; i < prefix.Length; i++)
        {
            int id = prefix[i] - 'a';
            if(curr.children[id] == null)
            {
                return 0;
            }
            curr = curr.children[id];
        }
        //當prefix是存在的,對prefix下的所有包含了MapSumNode的子節點的Value進行加總
        return GetSumDFS(curr);
    }
    //加總
    int GetSumDFS(MapSumNode node)
    {
        int sum = node.val;
        for(int i = 0; i < node.children.Count(); i++)
        {
            if(node.children[i] != null)
            {
                sum += GetSumDFS(node.children[i]);
            }
        }
        return sum;
    }
}

public class MapSumNode
{
    public MapSumNode[] children = new MapSumNode[26];
    public int val;
    public MapSumNode(){}
}