You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * Initialize your data structure here. */varTrie=function(){this.root=newTrieNode();};/** * Inserts a word into the trie. * @param {string} word * @return {void} */Trie.prototype.insert=function(word){letpatrol=this.root;for(leti=0;i<word.length;i++){patrol.data[word[i]]=patrol.data[word[i]]||newTrieNode();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){letpatrol=this.root;for(leti=0;i<word.length;i++){if((patrol=patrol.data[word[i]])===undefined){returnfalse;}}returnpatrol.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){letpatrol=this.root;for(leti=0;i<prefix.length;i++){if((patrol=patrol.data[prefix[i]])===undefined){returnfalse;}}returntrue;};functionTrieNode(){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
The text was updated successfully, but these errors were encountered: