力扣 leetcode 1202. 交换字符串中的元素 (python)

Topic:

给你一个字符串 s,以及该字符串中的一些「索引对」数组 pairs,其中 pairs[i] = [a, b] 表示字符串中的两个索引(编号从 0 开始)。
你可以 任意多次交换 在 pairs 中任意一对索引处的字符。
返回在经过若干次交换后,s 可以变成的按字典序最小的字符串。

Example_1:

输入:s = “dcab”, pairs = [[0,3],[1,2]]
输出:“bacd”
解释:
交换 s[0] 和 s[3], s = “bcad”
交换 s[1] 和 s[2], s = “bacd”

Example_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”

Example_3:

输入:s = “cba”, pairs = [[0,1],[1,2]]
输出:“abc”
解释:
交换 s[0] 和 s[1], s = “bca”
交换 s[1] 和 s[2], s = “bac”
交换 s[0] 和 s[1], s = “abc”

Solution:

本题整体思路基于并查集模板实现
首先是建图的过程:
将s中的值按照索引模拟成图的n个节点
每个索引是一个节点
之后通过pairs中的数组
将对应的可以互换的节点连通起来

之后是寻找联通的所有节点用于保存连通图
将根节点相同的放在一起
以根节点作为键
值为数组,存储以该根节点为根的并查集中所有节点下标

最后分别对每个根节点对应的连通关系按照字典序进行单独排列
将排序好的结果整合到res中即可完成

Code:

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 = collections.defaultdict(list)

        for node in range(len(s)):
            connected[uf.find(node)].append(node)


        # 重新赋值
        res = list(s)
        for nodes in connected.values():
            last = nodes
            string = sorted(res[d] for d in nodes)

            for e, f in zip(last,string):
                res[e] = f

        return "".join(res)

Result:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_50791900/article/details/112727756
今日推荐