|
| 1 | +var Node = function () { |
| 2 | + this.children = new Map(); |
| 3 | + this.isEnd = false; |
| 4 | +}; |
| 5 | + |
| 6 | +var WordDictionary = function () { |
| 7 | + this.root = new Node(); |
| 8 | +}; |
| 9 | + |
| 10 | +/** |
| 11 | + * @param {string} word |
| 12 | + * @return {void} |
| 13 | + */ |
| 14 | +WordDictionary.prototype.addWord = function (word) { |
| 15 | + let current = this.root; |
| 16 | + |
| 17 | + for (const chr of word) { |
| 18 | + if (!current.children.has(chr)) { |
| 19 | + current.children.set(chr, new Node()); |
| 20 | + } |
| 21 | + |
| 22 | + current = current.children.get(chr); |
| 23 | + } |
| 24 | + |
| 25 | + current.isEnd = true; |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * @param {string} word |
| 30 | + * @return {boolean} |
| 31 | + */ |
| 32 | +WordDictionary.prototype.search = function (word) { |
| 33 | + const stack = [[0, this.root]]; |
| 34 | + |
| 35 | + while (stack.length > 0) { |
| 36 | + const [index, currentNode] = stack.pop(); |
| 37 | + |
| 38 | + if (index === word.length) { |
| 39 | + if (currentNode.isEnd) { |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + if (word[index] === ".") { |
| 47 | + for (const [_, child] of currentNode.children) { |
| 48 | + stack.push([index + 1, child]); |
| 49 | + } |
| 50 | + |
| 51 | + continue; |
| 52 | + } |
| 53 | + |
| 54 | + if (currentNode.children.has(word[index])) { |
| 55 | + stack.push([index + 1, currentNode.children.get(word[index])]); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return false; |
| 60 | +}; |
| 61 | + |
| 62 | +/** |
| 63 | + * Your WordDictionary object will be instantiated and called as such: |
| 64 | + * var obj = new WordDictionary() |
| 65 | + * obj.addWord(word) |
| 66 | + * var param_2 = obj.search(word) |
| 67 | + */ |
0 commit comments