LeetCode677. 键值映射(Trie树)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode677. 键值映射(Trie树)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 題目
實(shí)現(xiàn)一個(gè) MapSum 類里的兩個(gè)方法,insert 和 sum。
對于方法 insert,你將得到一對(字符串,整數(shù))的鍵值對。字符串表示鍵,整數(shù)表示值。如果鍵已經(jīng)存在,那么原來的鍵值對將被替代成新的鍵值對。
對于方法 sum,你將得到一個(gè)表示前綴的字符串,你需要返回所有以該前綴開頭的鍵的值的總和。
輸入: insert("apple", 3), 輸出: Null 輸入: sum("ap"), 輸出: 3 輸入: insert("app", 2), 輸出: Null 輸入: sum("ap"), 輸出: 52. Trie樹解題
參考:Trie樹
class TrieNode { public:TrieNode *next[26];int count;TrieNode():count(0){memset(next,NULL,26*sizeof(TrieNode*));}~TrieNode(){} };class MapSum {TrieNode *root; public:/** Initialize your data structure here. */MapSum() {root = new TrieNode();}void insert(string key, int val) {TrieNode *cur = root;for(char ch:key){if(cur->next[ch-'a'] == NULL)cur->next[ch-'a'] = new TrieNode();cur = cur->next[ch-'a'];}cur->count = val;}int sum(string prefix) {TrieNode *cur = root;for(char ch:prefix){if(cur->next[ch-'a'] == NULL)return 0;elsecur = cur->next[ch-'a'];}int sumVal = 0;sumVal += cur->count;for(int i = 0; i < 26; ++i)if(cur->next[i])sumVal += sum(cur->next[i]);return sumVal;} private:int sum(TrieNode *root)//遞歸求和{int subsum = 0;if(root == NULL)return 0;subsum += root->count;for(int i = 0; i < 26; ++i)if(root->next[i])subsum += sum(root->next[i]);return subsum;} }; class trie{ // 2021.8.28 public:int v = 0;trie* next[26] = {NULL};void insert(string& s, int val){trie* cur = this;for(auto ch : s){if(!cur->next[ch-'a'])cur->next[ch-'a'] = new trie();cur = cur->next[ch-'a'];}cur->v = val;}void find(trie* root, string& s, int i, int &sum){if(!root) return;if(i<s.size()&&root->next[s[i]-'a'])find(root->next[s[i]-'a'], s, i+1, sum);else if(i==s.size()){sum += root->v;for(int j = 0; j < 26; ++j){if(root->next[j]){find(root->next[j], s, i, sum);}}}} }; class MapSum {trie* root; public:/** Initialize your data structure here. */MapSum() {root = new trie();}void insert(string key, int val) {root->insert(key,val);}int sum(string prefix) {int tot = 0;root->find(root, prefix, 0, tot);return tot;} };/*** Your MapSum object will be instantiated and called as such:* MapSum* obj = new MapSum();* obj->insert(key,val);* int param_2 = obj->sum(prefix);*/總結(jié)
以上是生活随笔為你收集整理的LeetCode677. 键值映射(Trie树)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: K 近邻法(K-Nearest Neig
- 下一篇: LeetCode 820. 单词的压缩编