力扣677.键值映射
-
字典树
- 求值时,先把node移动到前缀的末尾
- 再从末尾开始匹配
-
class MapSum { private: int val; MapSum* next[26]; public: MapSum() { val = 0; memset(next,0,sizeof(next)); } void insert(string key, int val) { MapSum* node = this; for(char c:key) { if(node->next[c-'a'] == NULL) node->next[c-'a'] = new MapSum(); node = node->next[c-'a']; } node->val = val; } int sum(string prefix) { MapSum* node = this; for(char c:prefix) { if(node->next[c-'a'] == NULL) return 0; node = node->next[c-'a']; } int sum = 0; match(node,sum); return sum; } void match(MapSum* node,int& sum) { //先加当前节点的值 sum += node->val; for(auto& next : node->next) //如果next存在 递归 if(next) match(next,sum); } };