forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1202.py
More file actions
23 lines (20 loc) · 670 Bytes
/
1202.py
File metadata and controls
23 lines (20 loc) · 670 Bytes
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 smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
p = list(range(len(s)))
def find(x):
if x != p[x]:
p[x] = find(p[x])
return p[x]
for i, j in pairs:
px, py = find(i), find(j)
if px != py:
p[px] = py
mem = collections.defaultdict(list)
for i, v in enumerate(p):
mem[find(v)].append(s[i])
for k in mem:
mem[k].sort(reverse=True)
res = []
for i in range(len(s)):
res.append(mem[find(i)].pop())
return "".join(res)