class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
toSort = []
result = [None]*len(s)
for i,j in pairs:
find = False
for parisSet in toSort:
if i in toSort or j in parisSet:
parisSet.update({i,j})
find = True
break
if not find:
toSort.append({i,j})
print(toSort)
for parisSet in toSort:
SortedStr = []
for i in parisSet:
SortedStr.append(s[i])
SortedStr.sort()
j = 0
for i in parisSet:
result[i]=SortedStr[j]
j += 1
return ''.join(result)
用了它的代码,运行成功
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, res, m = UF(len(s)), [], defaultdict(list)
for x,y in pairs:
uf.union(x,y)
for i in range(len(s)):
m[uf.find(i)].append(s[i])
for comp_id in m.keys():
m[comp_id].sort(reverse=True)
for i in range(len(s)):
res.append(m[uf.find(i)].pop())
return ''.join(res)