1202. 交换字符串中的元素(并查集)(傻瓜教程)(python)(LC)

这篇博客介绍了一种使用并查集算法解决字符串中元素交换的问题,旨在找到在给定交换条件下字符串字典序最小的排列。首先通过并查集建立字符串的连接关系,然后对每个连通分量内的字符进行排序,最终得到最小字典序的字符串。这种方法巧妙地将问题转化为图论中的连通分量,并结合字符串处理技巧实现解决方案。

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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Grayson Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值