|
| 1 | +/** |
| 2 | + * 前缀树 |
| 3 | + * https://leetcode-cn.com/problems/implement-trie-prefix-tree/ |
| 4 | +/** |
| 5 | + * Initialize your data structure here. |
| 6 | + */ |
| 7 | + var Trie = function () { |
| 8 | + this.value = ''; |
| 9 | + this.isWord = false; |
| 10 | + this.children = new Array(26); |
| 11 | +}; |
| 12 | + |
| 13 | +/** |
| 14 | + * Inserts a word into the trie. |
| 15 | + * @param {string} word |
| 16 | + * @return {void} |
| 17 | + */ |
| 18 | +Trie.prototype.insert = function (word) { |
| 19 | + let curLetter = this; |
| 20 | + for (let i = 0; i < word.length; i++) { |
| 21 | + const index = word[i].charCodeAt() - 'a'.charCodeAt(); |
| 22 | + if (!curLetter.children[index]) { |
| 23 | + curLetter.children[index] = new Trie(); |
| 24 | + curLetter.children[index].value = word[i]; |
| 25 | + } |
| 26 | + curLetter = curLetter.children[index]; |
| 27 | + } |
| 28 | + curLetter.isWord = true; |
| 29 | +}; |
| 30 | + |
| 31 | +/** |
| 32 | + * Returns if the word is in the trie. |
| 33 | + * @param {string} word |
| 34 | + * @return {boolean} |
| 35 | + */ |
| 36 | +Trie.prototype.search = function (word) { |
| 37 | + return this.find(word).flag && this.find(word).curLetter.isWord; |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * Returns if there is any word in the trie that starts with the given prefix. |
| 42 | + * @param {string} prefix |
| 43 | + * @return {boolean} |
| 44 | + */ |
| 45 | +Trie.prototype.startsWith = function (prefix) { |
| 46 | + return this.find(prefix).flag; |
| 47 | +}; |
| 48 | + |
| 49 | +Trie.prototype.find = function (prefix) { |
| 50 | + let curLetter = this; |
| 51 | + let flag = true; |
| 52 | + for (let i = 0; i < prefix.length; i++) { |
| 53 | + const index = prefix[i].charCodeAt() - 'a'.charCodeAt(); |
| 54 | + if (curLetter.children[index]) { |
| 55 | + curLetter = curLetter.children[index]; |
| 56 | + continue; |
| 57 | + } |
| 58 | + flag = false; |
| 59 | + break; |
| 60 | + } |
| 61 | + return { flag, curLetter }; |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Your Trie object will be instantiated and called as such: |
| 66 | + * var obj = new Trie() |
| 67 | + * obj.insert(word) |
| 68 | + * var param_2 = obj.search(word) |
| 69 | + * var param_3 = obj.startsWith(prefix) |
| 70 | + */ |
| 71 | +var obj = new Trie() |
| 72 | +obj.insert('apple') |
| 73 | +var param_2 = obj.search('app') |
| 74 | +var param_3 = obj.startsWith('app') |
| 75 | + |
| 76 | +console.log(obj, param_2, param_3); |
0 commit comments