-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0737-sentence-similarity-ii.py
51 lines (38 loc) · 1.57 KB
/
0737-sentence-similarity-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# time complexity: O((n + k) * m)
# space complexity: O(k*m)
from itertools import chain
from typing import List
class UnionFind:
def __init__(self, words: set):
self.parents = {w: w for w in words}
self.rank = {w: 1 for w in words}
def find(self, node: str):
if node != self.parents[node]:
self.parents[node] = self.find(self.parents[node])
return self.parents[node]
def union(self, nodeX: str, nodeY: str):
parentX = self.find(nodeX)
parentY = self.find(nodeY)
if parentX == parentY:
return
self.parents[parentX] = parentY
class Solution:
def areSentencesSimilarTwo(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool:
words = set(chain(*similarPairs))
if len(sentence1) != len(sentence2):
return False
for word1, word2 in zip(sentence1, sentence2):
words.add(word1)
words.add(word2)
disjointUnionSet = UnionFind(words)
for startVertex, endVertex in similarPairs:
disjointUnionSet.union(startVertex, endVertex)
for word1, word2 in zip(sentence1, sentence2):
if disjointUnionSet.find(word1) != disjointUnionSet.find(word2):
return False
return True
sentence1 = ["great", "acting", "skills"]
sentence2 = ["fine", "drama", "talent"]
similarPairs = [["great", "good"], ["fine", "good"],
["drama", "acting"], ["skills", "talent"]]
print(Solution().areSentencesSimilarTwo(sentence1, sentence2, similarPairs))