1202.cpp (1042B)
1 class UnionFind { 2 vector<int> root, rank; 3 4 public: 5 UnionFind(int n) : root(n), rank(n, 1) { iota(root.begin(), root.end(), 0); } 6 7 int find(int x) { 8 if (x == root[x]) return x; 9 return root[x] = find(root[x]); 10 } 11 12 void join(int x, int y) { 13 x = find(x), y = find(y); 14 15 if (x != y) { 16 if (rank[x] > rank[y]) swap(x, y); 17 root[y] = x; 18 rank[x] += x == y; 19 } 20 } 21 }; 22 23 class Solution { 24 public: 25 string smallestStringWithSwaps(string s, vector<vector<int>> &pairs) { 26 UnionFind uf(s.size()); 27 vector<vector<char>> vs(s.size()); 28 29 for (auto &p : pairs) 30 uf.join(p[0], p[1]); 31 32 for (int i = 0; i < s.size(); i++) 33 vs[uf.find(i)].push_back(s[i]); 34 35 for (auto &s : vs) 36 sort(s.rbegin(), s.rend()); 37 38 for (int i = 0; i < s.size(); i++) { 39 int index = uf.find(i); 40 s[i] = vs[index].back(); 41 vs[index].pop_back(); 42 } 43 return s; 44 } 45 };