实现一个 Trie (前缀树),包含 insert
, search
, 和 startsWith
这三个操作。
- 你可以假设所有的输入都是由小写字母
a-z
构成的。 - 保证所有输入均为非空字符串。
https://leetcode-cn.com/problems/implement-trie-prefix-tree/
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
答案
/**
* Initialize your data structure here.
*/
var Trie = function() {
this.map= new Map()
};
/**
* Inserts a word into the trie.
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
if (this.map.has(word)) {
return true
}
this.map.set(word, word)
};
/**
* Returns if the word is in the trie.
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function(word) {
return this.map.has(word)
};
/**
* Returns if there is any word in the trie that starts with the given prefix.
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function(prefix) {
for (let [key, value] of this.map) {
if (key.startsWith(prefix)) {
return true
}
}
return false
};
/**
* 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)
*/
感觉这个思路的难度不大,但是我的执行不知道为啥耗时这么高