package com.heu.wsq.leetcode.bingchaji;
import java.util.*;
/**
* 1202. 交换字符串中的元素
* @author wsq
* @date 2021/1/11
* 给你一个字符串 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"
*
* 链接:https://leetcode-cn.com/problems/smallest-string-with-swaps
*/
public class SmallestStringWithSwaps {
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs){
int n = pairs.size();
if (n == 0){
return s;
}
// 1.构建并查集, 保留元素之间的连通性、等价性
UnionFind unionFind = new UnionFind(s.length());
for (List<Integer> pair: pairs){
unionFind.union(pair.get(0), pair.get(1));
}
// 2.构建映射关系
char[] arr = s.toCharArray();
Map<Integer, PriorityQueue<Character>> hashMap = new HashMap<>();
for (int i = 0; i < arr.length; i++){
int root = unionFind.find(i);
if (hashMap.containsKey(root)){
hashMap.get(root).offer(arr[i]);
}else{
PriorityQueue queue = new PriorityQueue();
queue.offer(arr[i]);
hashMap.put(root, queue);
}
}
// 3、重组字符串
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++){
sb.append(hashMap.get(unionFind.find(i)).poll());
}
return sb.toString();
}
private class UnionFind{
private int[] parent;
private int[] rank;
public UnionFind(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;
rank[rootY] += 1;
}else if (rank[rootX] < rank[rootY]){
parent[rootX] = rootY;
}else{
parent[rootY] = rootX;
}
}
public int find(int x) {
int r = x;
while (r != parent[r]){
r = parent[r];
}
int k = x;
while (k != r){
int tmp = parent[k];
parent[k] = r;
k = tmp;
}
return r;
}
}
public static void main(String[] args) {
String s = "dcab";
List<List<Integer>> list = new ArrayList<>();
list.add(new ArrayList<Integer>(){{add(0); add(3);}});
list.add(new ArrayList<Integer>(){{add(1); add(2);}});
list.add(new ArrayList<Integer>(){{add(0); add(2);}});
SmallestStringWithSwaps ss = new SmallestStringWithSwaps();
String ans = ss.smallestStringWithSwaps(s, list);
System.out.println(ans);
}
}
1202. 交换字符串中的元素(并查集)
最新推荐文章于 2021-02-12 19:37:23 发布