|
| 1 | +class Solution { |
| 2 | + public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) { |
| 3 | + int n = s.length(); |
| 4 | + DisjointSet disjointSet = new DisjointSet(n); |
| 5 | + for (List<Integer> pair : pairs) { |
| 6 | + disjointSet.union(pair.get(0), pair.get(1)); |
| 7 | + } |
| 8 | + Map<Integer, PriorityQueue<Character>> map = new HashMap<>(); |
| 9 | + for (int i = 0; i < n; i++) { |
| 10 | + int root = disjointSet.find(i); |
| 11 | + map.computeIfAbsent(root, k -> new PriorityQueue<>()).offer(s.charAt(i)); |
| 12 | + } |
| 13 | + StringBuilder sb = new StringBuilder(); |
| 14 | + for (int i = 0; i < s.length(); i++) { |
| 15 | + sb.append(map.get(disjointSet.find(i)).poll()); |
| 16 | + } |
| 17 | + return sb.toString(); |
| 18 | + } |
| 19 | + |
| 20 | + private static final class DisjointSet { |
| 21 | + |
| 22 | + private final int[] root; |
| 23 | + private final int[] rank; |
| 24 | + public int unionCount; |
| 25 | + |
| 26 | + public DisjointSet(int size) { |
| 27 | + this.root = new int[size]; |
| 28 | + this.rank = new int[size]; |
| 29 | + for (int i = 0; i < size; i++) { |
| 30 | + this.root[i] = i; |
| 31 | + this.rank[i] = 1; |
| 32 | + } |
| 33 | + this.unionCount = size; |
| 34 | + } |
| 35 | + |
| 36 | + public void union(int nodeOne, int nodeTwo) { |
| 37 | + int rootOne = find(nodeOne); |
| 38 | + int rootTwo = find(nodeTwo); |
| 39 | + if (rootOne != rootTwo) { |
| 40 | + if (this.rank[rootOne] > this.rank[rootTwo]) { |
| 41 | + this.root[rootTwo] = rootOne; |
| 42 | + } else if (this.rank[rootOne] < this.rank[rootTwo]) { |
| 43 | + this.root[rootOne] = rootTwo; |
| 44 | + } else { |
| 45 | + this.root[rootTwo] = rootOne; |
| 46 | + this.rank[rootOne]++; |
| 47 | + } |
| 48 | + this.unionCount--; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | + public int find(int node) { |
| 54 | + if (node == root[node]) { |
| 55 | + return node; |
| 56 | + } |
| 57 | + return root[node] = find(root[node]); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments