1 Star 0 Fork 0

Roderland/algorithm

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Question1202.java 1.65 KB
一键复制 编辑 原始数据 按行查看 历史
Roderland 提交于 2021-02-15 00:17 +08:00 . add
package question;
import java.util.*;
public class Question1202 {
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
Union union = new Union(s.length());
for (int i = 0; i < pairs.size(); i++) {
List<Integer> list = pairs.get(i);
union.merge(list.get(0), list.get(1));
}
Map<Integer, Queue<Character>> map=new HashMap<>();
for (int i = 0; i < s.length(); i++) {
int key = union.find(i);
if (map.containsKey(key)) {
if (key!=i)
map.get(key).add(s.charAt(i));
} else {
Queue<Character> queue = new PriorityQueue<>();
queue.add(s.charAt(key));
if (key!=i)
queue.add(s.charAt(i));
map.put(key, queue);
}
}
//map.computeIfAbsent()
char[] chars = new char[s.length()];
for (int i = 0; i < chars.length; i++) {
int key = union.find(i);
chars[i] = map.get(key).poll();
}
return new String(chars);
}
private static class Union {
int[] root;
public Union(int n) {
root=new int[n];
for (int i = 0; i < root.length; i++) {
root[i]=i;
}
}
public boolean merge(int x, int y) {
x=find(x);
y=find(y);
if (x==y) return true;
root[x]=y;
return false;
}
public int find(int x) {
if (root[x]==x) return x;
root[x]=find(root[x]);
return root[x];
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/Roderland/algorithm.git
git@gitee.com:Roderland/algorithm.git
Roderland
algorithm
algorithm
master

搜索帮助