समस्या
हमें insert और sum विधियों के साथ एक MapSum क्लास को लागू करना है। insert विधि के लिए, हमें (स्ट्रिंग, पूर्णांक) का एक जोड़ा दिया जाएगा। स्ट्रिंग कुंजी को दर्शाता है और पूर्णांक मान को दर्शाता है। यदि कुंजी पहले से मौजूद थी, तो मूल कुंजी-मान जोड़ी को नए से ओवरराइड किया जाएगा।
sum विधि के लिए, हमें एक स्ट्रिंग दी जाएगी जो उपसर्ग को दर्शाती है, और हमें उन सभी जोड़ों के मानों का योग लौटाना होगा जिनकी कुंजी उस उपसर्ग से शुरू होती है।
उदाहरण
निम्नलिखित कोड है:
class Node { constructor(val) { this.num = 0; this.val = val; this.children = {}; } } class MapSum { constructor(){ this.root = new Node(''); } } MapSum.prototype.insert = function (key, val) { let node = this.root; for (const char of key) { if (!node.children[char]) { node.children[char] = new Node(char); } node = node.children[char]; } node.num = val; }; MapSum.prototype.sum = function (prefix) { let sum = 0; let node = this.root; for (const char of prefix) { if (!node.children[char]) { return 0; } node = node.children[char]; } const helper = (node) => { sum += node.num; const { children } = node; Object.keys(children).forEach((key) => { helper(children[key]); }); }; helper(node); return sum; }; const m = new MapSum(); console.log(m.insert('apple', 3)); console.log(m.sum('ap'));आउटपुट
undefined 3