|
| 1 | +/** |
| 2 | + * 425. Word Squares |
| 3 | + * https://leetcode.com/problems/word-squares/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an array of unique strings words, return all the word squares you can build from |
| 7 | + * words. The same word from words can be used multiple times. You can return the answer |
| 8 | + * in any order. |
| 9 | + * |
| 10 | + * A sequence of strings forms a valid word square if the kth row and column read the same |
| 11 | + * string, where 0 <= k < max(numRows, numColumns). |
| 12 | + * |
| 13 | + * - For example, the word sequence ["ball","area","lead","lady"] forms a word square because |
| 14 | + * each word reads the same both horizontally and vertically. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {string[]} words |
| 19 | + * @return {string[][]} |
| 20 | + */ |
| 21 | +var wordSquares = function(words) { |
| 22 | + const result = []; |
| 23 | + const prefixMap = new Map(); |
| 24 | + const wordLength = words[0].length; |
| 25 | + |
| 26 | + for (const word of words) { |
| 27 | + for (let i = 0; i < word.length; i++) { |
| 28 | + const prefix = word.slice(0, i); |
| 29 | + if (!prefixMap.has(prefix)) { |
| 30 | + prefixMap.set(prefix, []); |
| 31 | + } |
| 32 | + prefixMap.get(prefix).push(word); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + function buildSquare(currentSquare) { |
| 37 | + if (currentSquare.length === wordLength) { |
| 38 | + result.push([...currentSquare]); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + const prefix = currentSquare |
| 43 | + .map(word => word[currentSquare.length]) |
| 44 | + .join(''); |
| 45 | + |
| 46 | + const candidates = prefixMap.get(prefix) || []; |
| 47 | + for (const candidate of candidates) { |
| 48 | + currentSquare.push(candidate); |
| 49 | + buildSquare(currentSquare); |
| 50 | + currentSquare.pop(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + for (const word of words) { |
| 55 | + buildSquare([word]); |
| 56 | + } |
| 57 | + |
| 58 | + return result; |
| 59 | +}; |
0 commit comments