// 将同一个联通部分的字符拿出来, sort下
// 然后逐个填入....
class Solution {
private int[] father;
public int find(int x) {
if (x == father[x])
return x;
return father[x] = find(father[x]);
}
public void union(int u, int v) {
int x = find(u);
int y = find(v);
father[x] = y;
}
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
int n = s.length();
father = new int[n + 1];
for (int i = 1; i <= n; i++)
father[i] = i;
for (List<Integer> x : pairs) {
int u = x.get(0) + 1;
int v = x.get(1) + 1;
union(u, v);
}
for (int i = 1; i <= n; i++)
find(i);
HashMap<Integer, Integer> map = new HashMap<>();
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (!map.containsKey(father[i]))
map.put(father[i], cnt++);
}
ArrayList<ArrayList<Character> > res = new ArrayList<>(cnt);
for (int i = 0; i < cnt; i++)
res.add(new ArrayList<>());
ArrayList<Integer> index = new ArrayList<>(cnt);
for (int i = 0; i < cnt; i++)
index.add(0);
for (int i = 1; i <= n; i++) {
Integer x = map.get(father[i]);
res.get(x).add(s.charAt(i - 1));
}
for (int i = 0; i < cnt; i++){
Collections.sort(res.get(i));
}
StringBuilder sb = new StringBuilder(n);
for (int i = 1; i <= n; i++) {
int t = map.get(father[i]);
sb.append(res.get(t).get(index.get(t)));
index.set(t, index.get(t) + 1);
}
return sb.toString();
}
}
|