[leetcode] 1202. Smallest String With Swaps

Description

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.

You can swap the characters at any pair of indices in the given pairs any number of times.

Return the lexicographically smallest string that s can be changed to after using the swaps.

Example 1:

Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination: 
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"

Example 2:

Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination: 
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"

Example 3:

Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination: 
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"

Constraints:

  1. 1 <= s.length <= 10^5.
  2. 0 <= pairs.length <= 10^5.
  3. 0 <= pairs[i][0], pairs[i][1] < s.length
  4. s only contains lower case English letters.

分析

题目的意思是:给你一个数组的pairs,表示字符串能够进行位置交换的操作。这道题的关键点事怎么求解,我也没做出来,看了一下别人的解法,好像是要用到深度优先搜索,首先是构建一个词典d来存储paris的索引,然后再遍历这个字典d,下面的深度优先搜索找最佳的pair,有些地方我看的也不是很懂,希望有人多交流一下哈。

代码

class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
        d = defaultdict(list)
        for a,b in pairs:
            d[a].append(b)
            d[b].append(a)
        def dfs(x,A):
            if(x in d):
                A.append(x)
                for y in d.pop(x):
                    dfs(y,A)
        s=list(s)
        while(d):
            x=next(iter(d))
            A=[]
            dfs(x,A)
            A=sorted(A)
            B=sorted([s[i] for i in A])
            for i,b in enumerate(B):
                s[A[i]]=b
        return ''.join(s)

参考文献

[LeetCode] Clean Python DFS | O( n log n )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值