Open Tcdian opened 4 years ago
/**
* Initialize your data structure here.
*/
var Trie = function() {
this.root = new TrieNode();
};
/**
* Inserts a word into the trie.
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function(word) {
let patrol = this.root;
for (let i = 0; i < word.length; i++) {
patrol.data[word[i]] = patrol.data[word[i]] || new TrieNode();
patrol = patrol.data[word[i]];
}
patrol.isEnd = true;
};
/**
* Returns if the word is in the trie.
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function(word) {
let patrol = this.root;
for (let i = 0; i < word.length; i++) {
if ((patrol = patrol.data[word[i]]) === undefined) {
return false;
}
}
return patrol.isEnd;
};
/**
* 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) {
let patrol = this.root;
for (let i = 0; i < prefix.length; i++) {
if ((patrol = patrol.data[prefix[i]]) === undefined) {
return false;
}
}
return true;
};
function TrieNode() {
this.data = Object.create(null);
this.isEnd = 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)
*/
208. Implement Trie (Prefix Tree)
实现一个 Trie (前缀树),包含
insert
,search
, 和startsWith
这三个操作。Example
Note