समस्या
हमें सम्मिलित और योग विधियों के साथ MapSum वर्ग को लागू करने की आवश्यकता है। विधि डालने के लिए, हमें (स्ट्रिंग, पूर्णांक) की एक जोड़ी दी जाएगी। स्ट्रिंग कुंजी का प्रतिनिधित्व करती है और पूर्णांक मान का प्रतिनिधित्व करता है। यदि कुंजी पहले से मौजूद है, तो मूल कुंजी-मान युग्म को नए में बदल दिया जाएगा।
विधि योग के लिए, हमें उपसर्ग का प्रतिनिधित्व करने वाली एक स्ट्रिंग दी जाएगी, और हमें उन सभी जोड़ों के मानों का योग वापस करना होगा जिनकी कुंजी उपसर्ग से शुरू होती है।
उदाहरण
निम्नलिखित कोड है -
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