Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
题目原意:
实现字典树数据结构,包含插入,查找,前缀的方法。
注意:
可以假定所有输入由小写字母a-z组成。
解题思路:
字典树的每个节点至多由26个英文字母组成。
每个节点有两个属性:键值,是否为word的boolean值,以及由哈希表构成的字典。
代码如下:
首先构造函数,初始值为
this.root = {key: 'root', isWord: false};
/** * @constructor * Initialize your data structure here. */ var TrieNode = function (key) { return { key: key, isWord: false } }; var Trie = function () { this.root = TrieNode('root'); };
Insert 函数
遍历word的每一个字符,若字符在tree中不存在,则将字符插入新节点。每次插入新字符都要更新tree的原值。tree始终指向的是当前遍历的字符的值。
比如插入‘oath’ 之后,tree值变为:
{ key: 'root',
isWord: false,
o: {key: 'o', isWord: false, a:{ key: 'a',
isWord: false,
t: { key: 't',
isWord: false,
h: { key: 'h',
isWord: true }
}}}}
/** * @param {string} word * @return {void} * Inserts a word into the trie. */ Trie.prototype.insert = function (word) { var tree = this.root; for (var i in word) { var cur = word[i]; if (!tree[cur]) { tree[cur] = new TrieNode(cur); } tree = tree[cur]; } tree.isWord = true; };
search 函数
tree作为由root节点开始的字典,遍历单词的每一个字符,若当前字符在字典中出现,则进入下一层字典。直至当前word遍历完毕,字典isWord为true时返回true。其他情况均为false。
/** * @param {string} word * @return {boolean} * Returns if the word is in the trie. */ Trie.prototype.search = function (word) { var tree = this.root; for (var i in word) { if (!tree[word[i]]) { return false; } tree = tree[word[i]]; } if (tree.isWord) { return true; } else { return false; } };
startsWith 函数
和search函数类似,唯一不同的是startsWith只是比较前段部分的单词,因此可以省去最后是否为word的判断。
/** * @param {string} prefix * @return {boolean} * Returns if there is any word in the trie * that starts with the given prefix. */ Trie.prototype.startsWith = function (prefix) { var tree = this.root; for (var i in prefix) { if (!tree[prefix[i]]) { return false; } tree = tree[prefix[i]]; } return true; };