You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Solution {
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
int n = s.length();
UnionSet unionSet = new UnionSet(n);
for (List<Integer> pair : pairs) {
unionSet.union(pair.get(0), pair.get(1));
}
Map<Integer, Queue<Character>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.computeIfAbsent(unionSet.find(i), k -> new PriorityQueue<>()).add(s.charAt(i));
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(map.get(unionSet.find(i)).poll());
}
return sb.toString();
}
}
class UnionSet {
private int[] f;
private int n;
public UnionSet(int n) {
this.n = n;
f = new int[n];
for (int i = 0; i < n; i++) {
f[i] = i;
}
}
public int find(int x) {
return f[x] == x ? x : (f[x] = find(f[x]));
}
public void union(int x, int y) {
int xr = find(x);
int yr = find(y);
if (xr != yr) {
f[xr] = yr;
}
}
}
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: