1202. 交换字符串中的元素
问题描述:
给你一个字符串 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 中只含有小写英文字母
题目分析:
总体的思路是:并查集 + 哈希表,用优先队列维护字典序。
示例 1:
输入:s = "dcab", pairs = [[0,3],[1,2]]
输出:"bacd"
解释:
交换 s[0] 和 s[3], s = "bcad"
交换 s[1] 和 s[2], s = "bacd"
根据示例1我们可以得出下图:
[0,3]、[1,2]分别是两个集合,用优先队列存储。
最后遍历哈希表打印结果即可。
题解:
class Solution {
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
int len = s.length();
UnionFind uf = new UnionFind(len);
for (List<Integer> pair : pairs) {
uf.union(pair.get(0), pair.get(1));
}
HashMap<Integer, PriorityQueue<Character>> hashMap = new HashMap<>();
for (int i = 0; i < len; i++) {
int cur = uf.find(i);
if (!hashMap.containsKey(cur)) {
hashMap.put(cur, new PriorityQueue<>());
}
hashMap.get(cur).offer(s.charAt(i));
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append(hashMap.get(uf.find(i)).poll());
}
return sb.toString();
}
//并查集模板
class UnionFind {
int[] parent;
public UnionFind(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public void union(int index1, int index2) {
parent[find(index2)] = find(index1);
}
public int find(int index) {
if (parent[index] != index) {
parent[index] = find(parent[index]);
}
return parent[index];
}
}
}