1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: class UF: def __init__(self, n): self.p = list(range(n)) def union(self, x, y): self.p[self.find(x)] = self.find(y) def find(self, x): if x != self.p[x]: self.p[x] = self.find(self.p[x]) return self.p[x] uf, m, ans = UF(len(s)), defaultdict(list), [] for a, b in pairs: uf.union(a, b) for i in range(len(s)): m[uf.find(i)].append(s[i]) for id in m.keys(): m[id].sort(reverse=True) for i in range(len(s)): ans.append(m[uf.find(i)].pop()) return ''.join(ans)
|