forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1258.py
23 lines (20 loc) · 766 Bytes
/
1258.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]:
parent = collections.defaultdict(str)
data = collections.defaultdict(list)
def find(x):
if x not in parent:
parent[x] = x
if x != parent[x]:
parent[x] = find(parent[x])
return parent[x]
for p, q in synonyms:
x, y = find(p), find(q)
if x != y:
parent[x] = y
for k in parent:
data[find(k)].append(k)
res = [[]]
for w in text.split(" "):
res = [it + [v] for it in res for v in data[find(w)] or [w]]
return sorted([" ".join(it) for it in res])