|
| 1 | +/** |
| 2 | + * 1032. Stream of Characters |
| 3 | + * https://leetcode.com/problems/stream-of-characters/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Design an algorithm that accepts a stream of characters and checks if a suffix of these |
| 7 | + * characters is a string of a given array of strings words. |
| 8 | + * |
| 9 | + * For example, if words = ["abc", "xyz"] and the stream added the four characters (one by one) |
| 10 | + * 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix "xyz" of the characters |
| 11 | + * "axyz" matches "xyz" from words. |
| 12 | + * |
| 13 | + * Implement the StreamChecker class: |
| 14 | + * - StreamChecker(String[] words) Initializes the object with the strings array words. |
| 15 | + * - boolean query(char letter) Accepts a new character from the stream and returns true if any |
| 16 | + * non-empty suffix from the stream forms a word that is in words. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {string[]} words |
| 21 | + */ |
| 22 | +var StreamChecker = function(words) { |
| 23 | + this.trie = {}; |
| 24 | + this.stream = []; |
| 25 | + |
| 26 | + words.forEach(word => buildTrie(word, this.trie)); |
| 27 | + |
| 28 | + function buildTrie(word, trie) { |
| 29 | + let node = trie; |
| 30 | + for (let i = word.length - 1; i >= 0; i--) { |
| 31 | + const char = word[i]; |
| 32 | + node[char] = node[char] || {}; |
| 33 | + node = node[char]; |
| 34 | + } |
| 35 | + node.isEnd = true; |
| 36 | + } |
| 37 | +}; |
| 38 | + |
| 39 | +/** |
| 40 | + * @param {character} letter |
| 41 | + * @return {boolean} |
| 42 | + */ |
| 43 | +StreamChecker.prototype.query = function(letter) { |
| 44 | + this.stream.push(letter); |
| 45 | + let node = this.trie; |
| 46 | + |
| 47 | + for (let i = this.stream.length - 1; i >= 0; i--) { |
| 48 | + const char = this.stream[i]; |
| 49 | + if (!node[char]) return false; |
| 50 | + node = node[char]; |
| 51 | + if (node.isEnd) return true; |
| 52 | + } |
| 53 | + |
| 54 | + return false; |
| 55 | +}; |
0 commit comments