Leetcode Leetcode 1202. Exchange elements in a string (python)

Topic:

Give you a string s, and some "index pairs" array pairs in the string, where pairs[i] = [a, b] represents two indexes in the string (numbering starts from 0).
You can swap the characters at any pair of indexes in pairs as many times as you want.
Return the smallest string lexicographically that s can become after several exchanges.

Example_1:

Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explanation:
exchange s[0] and s[3], s = "bcad"
exchange s[1 ] And s[2], s = "bacd"

Example_2:

Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explanation:
Exchange s[0] and s[3], s = " "bcad"
exchanges s[0] and s[2], s = "acbd"
exchanges s[1] and s[2], s = "abcd"

Example_3:

Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explanation:
exchange s[0] and s[1], s = "bca"
exchange s[1 ] And s[2], s = "bac"
swap s[0] and s[1], s = "abc"

Solution:

The overall idea of ​​this question is based on the union search template implementation. The
first is the process of building a graph:
the value in s is simulated into n nodes of the graph according to the index.
Each index is a node.
Then
the corresponding interchangeable nodes are changed through the array in pairs. Connect

Then it is to find all the nodes of China Unicom to save the connected graph.
Put the same root nodes together,
use the root node as the key
value as an array, store the root node as the root and check all the node subscripts in the set

Finally, the connected relationships corresponding to each root node are individually arranged in lexicographic order, and
the sorted results are integrated into res to complete

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:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112727756