【发布时间】:2020-02-25 14:31:49
【问题描述】:
在构建 trie 时,是否将字符串/句子存储在其分支末尾以便在分支末尾轻松访问它?有些人会这样做,我有时也会这样做,但我应该这样做吗?
有时(尤其是使用 LeetCode),我会收到此错误:
Line # in solution.js
AutocompleteSystem.prototype.dfs = function(root, char, foundStrings) {
^
RangeError: Maximum call stack size exceeded
该错误仅表示我的深度优先搜索功能超出了调用堆栈。
除了我的 Trie 类之外,我没有其他任何改变:
class Trie {
constructor() {
this.root = {};
this.end = '#';
}
insert(sentence, times) {
let current = this.root;
for (const char of sentence) {
if (current[char] == null) {
current[char] = {};
}
current = current[char];
}
current[this.end] = true; // This works fine, submission accepted.
// If I store the string here like so:
// current[this.end] = sentence; I get the error.
current.times = current.times + 1 || times;
}
}
// As you can see, the dfs function won't affect
// if I store the string at the end of each branch or not
// because it doesn't use the value of #
const dfs = function(root, char, foundStrings) {
for (const key in root) {
// If reach the end of a branch:
if (key === '#') {
// If the current times not already in foundStrings:
if (!foundStrings[root.times]) {
// Initiate an empty array with the new times as key
// to store strings later:
foundStrings[root.times] = [];
}
// Else, push the found string into foundStrings, grouped by times:
foundStrings[root.times].push(char);
// Sort all strings in the same group:
foundStrings[root.times].sort();
}
// Keep searching:
this.dfs(root[key], char + key, foundStrings);
}
}
Trie 类只是从 string[]: sentences 构建一个 trie,我没有对结束符号 # 做任何其他事情,所以没有其他错误。
【问题讨论】:
-
您是否将字符串存储在其分支的末尾? 不,这会破坏构建 Trie 的全部意义(这是为了节省空间而不是存储重复的字符) .最好的办法是保留一个包含单词的字符串(从根开始)直到您所在的节点。显然,根据情况(输入大小),您可以将整个单词保存在树的叶子中,但我不建议这样做。
-
谢谢。你写的有道理。有些人确实将字符放入递归函数并更新它并在 dfs 的末尾返回它,但有些人只是将字符串存储在末尾。
-
由于错误发生在
dfs中,因此了解该函数的外观可能会很有用。 -
我在上面添加了
dfs函数。
标签: javascript algorithm trie