1202. 交换字符串中的元素
给你一个字符串 s,以及该字符串中的一些「索引对」数组 pairs,其中 pairs[i] = [a, b] 表示字符串中的两个索引(编号从 0 开始)。
你可以 任意多次交换 在 pairs 中任意一对索引处的字符。
返回在经过若干次交换后,s 可以变成的按字典序最小的字符串。
示例 1:
输入:s = "dcab", pairs = [[0,3],[1,2]]
输出:"bacd"
解释:
交换 s[0] 和 s[3], s = "bcad"
交换 s[1] 和 s[2], s = "bacd"
示例 2:
输入:s = "dcab", pairs = [[0,3],[1,2],[0,2]]
输出:"abcd"
解释:
交换 s[0] 和 s[3], s = "bcad"
交换 s[0] 和 s[2], s = "acbd"
交换 s[1] 和 s[2], s = "abcd"
算法
基本思路:
1.这道题的重点在于将题干条件” 任意多次交换 在 pairs 中任意一对索引处的字符“翻译为“连通分量”
2.有了连通分量的概念后用dps,bps,还是并查集处理问题都可以
3.最后才是对字符串本身的处理
并查集
class UnionFind:
1.初始化
def __init__(self,s):
self.father = {i:i for i in range(len(s))}
2.查找
def find(self,x):
root = x
while self.father[root] != root:
root = self.father[root]
# 路径压缩
while x != root:
original_father = self.father[x]
self.father[x] = root
x = original_father
return root
3.合并
def merge(self,x,y):
root_x,root_y = self.find(x),self.find(y)
if root_x != root_y:
self.father[root_x] = root_y
解题
class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
1.建图
uf = UnionFind(s)
for x,y in pairs:
uf.merge(x,y)
2.获取联通节点
获取联通节点是本题的一个特点,值得借鉴
connected_components = collections.defaultdict(list)
for node in range(len(s)):
connected_components[uf.find(node)].append(node)
3.字符串处理
for nodes in connected_components.values():
indices = nodes
string = sorted(res[node] for node in nodes)
for i,ch in zip(indices,string):
res[i] = ch
完整代码
class UnionFind:
def __init__(self,s):
self.father = {i:i for i in range(len(s))}
def find(self,x):
root = x
while self.father[root] != root:
root = self.father[root]
# 路径压缩
while x != root:
original_father = self.father[x]
self.father[x] = root
x = original_father
return root
def merge(self,x,y):
root_x,root_y = self.find(x),self.find(y)
if root_x != root_y:
self.father[root_x] = root_y
class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
# 并查集建图
uf = UnionFind(s)
for x,y in pairs:
uf.merge(x,y)
# 获取联通节点
connected_components = collections.defaultdict(list)
for node in range(len(s)):
connected_components[uf.find(node)].append(node)
res = list(s)
# 重新赋值
for nodes in connected_components.values():
indices = nodes
string = sorted(res[node] for node in nodes)
for i,ch in zip(indices,string):
res[i] = ch
return "".join(res)
这篇博客介绍了一种使用并查集算法解决字符串中元素交换的问题,旨在找到在给定交换条件下字符串字典序最小的排列。首先通过并查集建立字符串的连接关系,然后对每个连通分量内的字符进行排序,最终得到最小字典序的字符串。这种方法巧妙地将问题转化为图论中的连通分量,并结合字符串处理技巧实现解决方案。
傻瓜教程)(python)(LC)&spm=1001.2101.3001.5002&articleId=112674853&d=1&t=3&u=96433a4a6fff4c3f9514a18d52118ff0)
3万+

被折叠的 条评论
为什么被折叠?



