|
| 1 | +/** |
| 2 | + * 208. Implement Trie (Prefix Tree) |
| 3 | +Medium |
| 4 | +Topics |
| 5 | +Companies |
| 6 | +A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. |
| 7 | +
|
| 8 | +Implement the Trie class: |
| 9 | +
|
| 10 | +Trie() Initializes the trie object. |
| 11 | +void insert(String word) Inserts the string word into the trie. |
| 12 | +boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. |
| 13 | +boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. |
| 14 | +
|
| 15 | +1 <= word.length, prefix.length <= 2000 |
| 16 | +word and prefix consist only of lowercase English letters. |
| 17 | +At most 3 * 104 calls in total will be made to insert, search, and startsWith. |
| 18 | + */ |
| 19 | + |
| 20 | +// var Trie = function() { |
| 21 | +// node |
| 22 | +// }; |
| 23 | + |
| 24 | +class TrieNode { |
| 25 | + constructor() { |
| 26 | + this.children = {}; |
| 27 | + this.words = new Set(); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class Trie { |
| 32 | + constructor() { |
| 33 | + this.root = new TrieNode(); |
| 34 | + } |
| 35 | + |
| 36 | + traverse(word) { |
| 37 | + let node = this.root; |
| 38 | + for (let char of word) { |
| 39 | + node = node.children[char]; |
| 40 | + if (!node) return null; |
| 41 | + } |
| 42 | + return node; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * @param {string} word |
| 48 | + * @return {void} |
| 49 | + */ |
| 50 | +Trie.prototype.insert = function (word) { |
| 51 | + let node = this.root; |
| 52 | + for (const char of word) { |
| 53 | + if (!node.children[char]) { |
| 54 | + node.children[char] = new TrieNode(); |
| 55 | + } |
| 56 | + node = node.children[char]; |
| 57 | + } |
| 58 | + node.words.add(word); |
| 59 | +}; |
| 60 | + |
| 61 | +/** |
| 62 | + * @param {string} word |
| 63 | + * @return {boolean} |
| 64 | + */ |
| 65 | +Trie.prototype.search = function (word) { |
| 66 | + let node = this.traverse(word); |
| 67 | + return !!node && node.words.has(word); |
| 68 | +}; |
| 69 | + |
| 70 | +/** |
| 71 | + * @param {string} prefix |
| 72 | + * @return {boolean} |
| 73 | + */ |
| 74 | +Trie.prototype.startsWith = function (prefix) { |
| 75 | + let node = this.traverse(prefix); |
| 76 | + return !!node; |
| 77 | +}; |
| 78 | + |
| 79 | +/** |
| 80 | + * Your Trie object will be instantiated and called as such: |
| 81 | + * var obj = new Trie() |
| 82 | + * obj.insert(word) |
| 83 | + * var param_2 = obj.search(word) |
| 84 | + * var param_3 = obj.startsWith(prefix) |
| 85 | + */ |
0 commit comments