forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
35 lines (32 loc) · 1.01 KB
/
Solution.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
class Solution:
def areSentencesSimilarTwo(
self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]
) -> bool:
if len(sentence1) != len(sentence2):
return False
n = len(similarPairs)
p = list(range(n << 1))
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
words = {}
idx = 0
for a, b in similarPairs:
if a not in words:
words[a] = idx
idx += 1
if b not in words:
words[b] = idx
idx += 1
p[find(words[a])] = find(words[b])
for i in range(len(sentence1)):
if sentence1[i] == sentence2[i]:
continue
if (
sentence1[i] not in words
or sentence2[i] not in words
or find(words[sentence1[i]]) != find(words[sentence2[i]])
):
return False
return True