【发布时间】:2023-03-27 19:07:01
【问题描述】:
我每次都会为不同的测试用例生成相同的答案。在我的代码中,我尝试创建 Trie 数据结构来存储和检索字符串的最高优先级以供后续查询。例如。我想创建一个搜索引擎类型模式。
请帮我解决我的问题-
输入 -
黑客地球 10
黑客5
class TrieNode {
constructor(priority) {
this.priority = priority;
this.children = []
for (let i = 0; i < 26; i++) {
this.children.push(null)
}
}
}
class Trie {
constructor() {
this.root = new TrieNode(-1);
}
createNode(priority) {
let obj = new TrieNode(priority)
return obj;
}
max(a, b) {
if (a > b) {
return a;
}
return b;
}
insertNode(word, priority) {
let ptr = this.root;
for (let i = 0; i < word.length; i++) {
if (ptr.children[word[i] - 'a'] != null) {
ptr.children[word[i] - 'a'].priority = this.max(ptr.children[word[i] - 'a'].priority, priority)
} else {
ptr.children[word[i] - 'a'] = this.createNode(priority)
}
ptr = ptr.children[word[i] - 'a']
}
}
checkNode(word) {
let ptr = this.root;
for (let i = 0; i < word.length; i++) {
if (ptr.children[word[i] - 'a'] === null) {
return -1;
}
ptr = ptr.children[word[i] - 'a']
}
return ptr.priority;
}
}
let a = new Trie();
a.insertNode("hackerearth", 10);
a.insertNode("hackerman", 5);
console.log(a.root.children['h' - 'a'])
console.log(a.checkNode("hackerf"))
结果总是一样的:
TrieNode {
priority: 10,
children: [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
NaN: TrieNode { priority: 10, children: [Array] }
]
}
10
【问题讨论】:
-
注意:可以使用
this.children = Array(25).fill(null)设置数组 -
谢谢你,@epascarello,但主要问题是我试图实现的整个 trie 数据结构
-
你的减法没有意义。我假设您希望 A 的字符代码基于 0?
"hello".split('').map(x => x.charCodeAt(0) - "a".charCodeAt(0))
标签: javascript class oop data-structures trie