|
| 1 | +/** |
| 2 | + * 1258. Synonymous Sentences |
| 3 | + * https://leetcode.com/problems/synonymous-sentences/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti] |
| 7 | + * indicates that si and ti are equivalent strings. You are also given a sentence text. |
| 8 | + * |
| 9 | + * Return all possible synonymous sentences sorted lexicographically. |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * @param {string[][]} synonyms |
| 14 | + * @param {string} text |
| 15 | + * @return {string[]} |
| 16 | + */ |
| 17 | +var generateSentences = function(synonyms, text) { |
| 18 | + const graph = new Map(); |
| 19 | + |
| 20 | + for (const [word1, word2] of synonyms) { |
| 21 | + if (!graph.has(word1)) graph.set(word1, []); |
| 22 | + if (!graph.has(word2)) graph.set(word2, []); |
| 23 | + graph.get(word1).push(word2); |
| 24 | + graph.get(word2).push(word1); |
| 25 | + } |
| 26 | + |
| 27 | + const words = text.split(' '); |
| 28 | + const allCombinations = []; |
| 29 | + backtrack(0, []); |
| 30 | + return allCombinations.sort(); |
| 31 | + |
| 32 | + function findSynonyms(word) { |
| 33 | + if (!graph.has(word)) return [word]; |
| 34 | + |
| 35 | + const visited = new Set(); |
| 36 | + const queue = [word]; |
| 37 | + const synonymGroup = []; |
| 38 | + |
| 39 | + while (queue.length > 0) { |
| 40 | + const current = queue.shift(); |
| 41 | + if (visited.has(current)) continue; |
| 42 | + |
| 43 | + visited.add(current); |
| 44 | + synonymGroup.push(current); |
| 45 | + |
| 46 | + for (const neighbor of graph.get(current)) { |
| 47 | + if (!visited.has(neighbor)) { |
| 48 | + queue.push(neighbor); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return synonymGroup.sort(); |
| 54 | + } |
| 55 | + |
| 56 | + function backtrack(index, currentSentence) { |
| 57 | + if (index === words.length) { |
| 58 | + allCombinations.push(currentSentence.join(' ')); |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + const synonyms = findSynonyms(words[index]); |
| 63 | + for (const synonym of synonyms) { |
| 64 | + currentSentence.push(synonym); |
| 65 | + backtrack(index + 1, currentSentence); |
| 66 | + currentSentence.pop(); |
| 67 | + } |
| 68 | + } |
| 69 | +}; |
0 commit comments