- Leetcode-208Implement Trie (Pref
- 208. Implement Trie (Prefix Tree
- 208. Implement Trie (Prefix Tree
- 208. Implement Trie (Prefix Tree
- 208. Implement Trie (Prefix Tree
- 208. Implement Trie (Prefix Tree
- 208. Implement Trie (Prefix Tree
- 208. Implement Trie (Prefix Tree
- 208 Implement Trie (Prefix Tree)
- implement-trie-prefix-tree
Trie 前缀树是一种树形数据结构,用于高效存储和检索字符串数据集中的键。
请你实现 Trie 类:
Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
- 时间复杂度 O(n),空间复杂度O(n)
- Runtime: 196 ms, faster than 91.79%
- Memory Usage: 53.7 MB, less than 87.84%
var Trie = function() {
this.children = {};
};
/**
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
let node = this.children;
for (const ch of word) {
if (!node[ch]) {
node[ch] = {};
}
node = node[ch];
}
node.isEnd = true;
};
/**
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function(word) {
const node = this.startsWith(word);
return node !== undefined && node.isEnd !== undefined;
};
/**
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function(prefix) {
let node = this.children;
for (const ch of prefix) {
if (!node[ch]) {
return false;
}
node = node[ch];
}
return node;
};
/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/
暴力法
- 时间复杂度O(n),空间复杂度O(1)
- Runtime: 368 ms, faster than 14.13%
- Memory Usage: 49.1 MB, less than 99.78%
var Trie = function() {
this.res = [];
};
Trie.prototype.insert = function(word) {
this.res.push(word);
};
Trie.prototype.search = function(word) {
return this.res.includes(word);
};
Trie.prototype.startsWith = function(prefix) {
for (let i = 0; i < this.res.length; i++) {
const val = this.res[i]
if (val.indexOf(prefix) === 0) {
return true;
}
}
return false;
};
网友评论