LeetCode 题解工作台

交换字符串中的元素

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

category

7

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们注意到,索引对具有传递性,即如果 与 可交换,而 与 可交换,那么 与 也可交换。因此,我们可以考虑使用并查集维护这些索引对的连通性,将属于同一个连通分量的字符按照字典序排序。 最后,遍历字符串,对于当前位置的字符,我们将其替换为该连通分量中最小的字符,然后从该连通分量中取出该字符,继续遍历字符串即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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"

示例 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"

 

提示:

  • 1 <= s.length <= 10^5
  • 0 <= pairs.length <= 10^5
  • 0 <= pairs[i][0], pairs[i][1] < s.length
  • s 中只含有小写英文字母
lightbulb

解题思路

方法一:并查集

我们注意到,索引对具有传递性,即如果 aabb 可交换,而 bbcc 可交换,那么 aacc 也可交换。因此,我们可以考虑使用并查集维护这些索引对的连通性,将属于同一个连通分量的字符按照字典序排序。

最后,遍历字符串,对于当前位置的字符,我们将其替换为该连通分量中最小的字符,然后从该连通分量中取出该字符,继续遍历字符串即可。

时间复杂度 O(n×logn+m×α(m))O(n \times \log n + m \times \alpha(m)),空间复杂度 O(n)O(n)。其中 nnmm 分别为字符串的长度和索引对的数量,而 α\alpha 为阿克曼函数的反函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
        def find(x: int) -> int:
            if p[x] != x:
                p[x] = find(p[x])
            return p[x]

        n = len(s)
        p = list(range(n))
        for a, b in pairs:
            p[find(a)] = find(b)
        d = defaultdict(list)
        for i, c in enumerate(s):
            d[find(i)].append(c)
        for i in d.keys():
            d[i].sort(reverse=True)
        return "".join(d[find(i)].pop() for i in range(n))
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for understanding of graph theory, particularly connected components.

  • question_mark

    Pay attention to how the candidate handles sorting within each connected component.

  • question_mark

    Check for optimization in the approach, especially in handling large inputs.

warning

常见陷阱

外企场景
  • error

    Forgetting to sort the characters within each connected component.

  • error

    Failing to recognize that the problem is essentially about identifying connected components in a graph.

  • error

    Not handling edge cases like no pairs or the minimum string length.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the swaps are limited to certain indices?

  • arrow_right_alt

    How would you optimize this problem for larger strings or more pairs?

  • arrow_right_alt

    Can this problem be solved with dynamic programming instead of graph traversal?

help

常见问题

外企场景

交换字符串中的元素题解:数组·哈希·扫描 | LeetCode #1202 中等