题目
https://leetcode-cn.com/problems/smallest-string-with-swaps/
并查集
分析示例可以发现索引交换具有传递性,如果两个索引对出现公共索引,那么索引对中的下标可以任意交换
将可任意交换次序的部分按照字典序升序排序,得到的字符串的字典序就是最小的;
问题可以转化为下标连通分量的问题。
先根据索引对集合将索引合并,这样可任意交换的索引同处一个连通分量。由于字符串每个索引位置的字符都应取该索引对应连通分量中的字典序的最小值,因此构建一个哈希表,其键值为索引对应连通分量的根节点(代表元),值为同一个连通分量的字符集合,使用优先队列维护字典序。这样构建字符串时取每个索引对应的连通分量中字符集合的最小字符即可。下面代码在构建并查集时使用了按秩压缩和完全路径压缩的技巧
class Solution {
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
if (pairs.size() == 0) return s;
int len = s.length();
UnioFind unionFind = new UnioFind(len);
for (List<Integer> pair : pairs) {
int index1 = pair.get(0);
int index2 = pair.get(1);
unionFind.union(index1, index2);
}
char[] arr = s.toCharArray();
// key 为每一个索引所在连通分量的代表元 values: 同一个连通分量的字符集合
Map<Integer, PriorityQueue<Character>> hashMap = new HashMap<>(len);
for (int i = 0; i < len; i++) {
int root = unionFind.find(i);
if (hashMap.containsKey(root)) {
hashMap.get(root).offer(arr[i]);
} else {
PriorityQueue<Character> queue = new PriorityQueue<>();
queue.offer(arr[i]);
hashMap.put(root, queue);
}
}
StringBuilder bd = new StringBuilder();
for (int i = 0; i < len; i++) {
int root = unionFind.find(i);
bd.append(hashMap.get(root).poll());
}
return bd.toString();
}
private class UnioFind {
private int[] parent;
/**
* 以i为根节点的子树的高度(引入了路径压缩以后该定义并不明确)
*/
private int[] rank;
public UnioFind(int n) {
this.parent = new int[n];
this.rank = new int[n];
for (int i = 0; i < n; i++) {
this.parent[i] = i;
this.rank[i] = 1;
}
}
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY)
return;
if (rank[rootX] == rank[rootY]) {
parent[rootX] = rootY;
// 此时以rootY为根节点的树的高度增加了 1
rank[rootY] += 1;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
// 此时以rootY为根结点的树的高度不变
} else {
parent[rootY] = rootX;
// 同理以rootX为根结点的树的高度不变
}
}
// 完全路径压缩
public int find(int x) {
if (x != parent[x]) {
parent[x] = find(parent[x]);
}
return parent[x];
}
}
}