5110. 近义词句子

给你一个近义词表 synonyms 和一个句子 text , synonyms 表中是一些近义词对 ,你可以将句子 text 中每个单词用它的近义词来替换。

请你找出所有用近义词替换后的句子,按 字典序排序 后返回。

 

示例 1:

输入:
synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]],
text = "I am happy today but was sad yesterday"
输出:
["I am cheerful today but was sad yesterday",
"I am cheerful today but was sorrow yesterday",
"I am happy today but was sad yesterday",
"I am happy today but was sorrow yesterday",
"I am joy today but was sad yesterday",
"I am joy today but was sorrow yesterday"]
 

提示:

0 <= synonyms.length <= 10
synonyms[i].length == 2
synonyms[0] != synonyms[1]
所有单词仅包含英文字母,且长度最多为 10 。
text 最多包含 10 个单词,且单词间用单个空格分隔开。

 

题解:

并查集深搜,用的是自创的并查集方法。

class Solution:
    def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]:
        p, text = {}, text.split()
        for i, j in synonyms:
            p[i], p[j] = p.get(i, [i]), p.get(j, [j])
            if p[i] is not p[j]:
                p[i] += p[j]
                for k in p[j]:
                    p[k] = p[i]
        ans, n = [], len(text)
        def f(i, t):
            if i == n:
                ans.append(' '.join(t))
            else:
                g = lambda x: f(i + 1, t + [x])
                [*map(g, p[text[i]] if text[i] in p else [text[i]])]
        f(0, [])
        return sorted(ans)

 

你可能感兴趣的:(5110. 近义词句子)