208.实现 Trie (前缀树)

实现 Trie (前缀树)

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;
};

208.实现 Trie (前缀树)
https://leetcode.lz5z.com/208.implement-trie-prefix-tree/
作者
tickli
发布于
2024年6月23日
许可协议