Trie(前缀树)是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。
解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var Trie = function () { this.root = {}; }; Trie.prototype.insert = function (word) { let node = this.root; for (const ch of word) { if (!node[ch]) node[ch] = {}; node = node[ch]; } node.isEnd = true; }; Trie.prototype.search = function (word) { let node = this.root; for (const ch of word) { if (!node[ch]) return false; node = node[ch]; } return !!node.isEnd; }; Trie.prototype.startsWith = function (prefix) { let node = this.root; for (const ch of prefix) { if (!node[ch]) return false; node = node[ch]; } return true; };
|