目标
给你一个字符串 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 中只含有小写英文字母
思路
有一个字符串 s 和 一个索引对数组 pairs,可以任意交换索引对位置上的字符,求能够得到的字典序最小的字符串。
并查集,将所有可交换的位置分到一组,在组内排序然后放到对应的位置上即可。
代码
/**
* @date 2026-12-02 10:00
*/
public class SmallestStringWithSwaps1202 {
class UnionFind {
int[] fa;
public UnionFind(int n) {
this.fa = new int[n];
Arrays.setAll(this.fa, i -> i);
}
public void merge(int a, int b) {
int x = find(a);
int y = find(b);
if (x < y) {
fa[y] = x;
} else if (x > y) {
fa[x] = y;
}
}
public int find(int a) {
if (fa[a] != a) {
fa[a] = find(fa[a]);
}
return fa[a];
}
}
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
char[] chars = s.toCharArray();
int n = s.length();
UnionFind uf = new UnionFind(n);
for (List<Integer> pair : pairs) {
uf.merge(pair.get(0), pair.get(1));
}
Map<Integer, PriorityQueue<Character>> map = new HashMap<>();
Map<Integer, Deque<Integer>> indexMap = new HashMap<>();
for (int i = 0; i < n; i++) {
int j = uf.find(i);
map.putIfAbsent(j, new PriorityQueue<>());
indexMap.putIfAbsent(j, new ArrayDeque<>());
map.get(j).add(chars[i]);
indexMap.get(j).add(i);
}
for (Map.Entry<Integer, PriorityQueue<Character>> entry : map.entrySet()) {
int k = entry.getKey();
Deque<Integer> v = indexMap.get(k);
while (!v.isEmpty()){
chars[v.poll()] = entry.getValue().poll();
}
}
return new String(chars);
}
}
性能
