forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
31 lines (31 loc) · 806 Bytes
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
int n = s.size();
int p[n];
iota(p, p + n, 0);
vector<char> d[n];
function<int(int)> find = [&](int x) -> int {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
};
for (auto e : pairs) {
int a = e[0], b = e[1];
p[find(a)] = find(b);
}
for (int i = 0; i < n; ++i) {
d[find(i)].push_back(s[i]);
}
for (auto& e : d) {
sort(e.rbegin(), e.rend());
}
for (int i = 0; i < n; ++i) {
auto& e = d[find(i)];
s[i] = e.back();
e.pop_back();
}
return s;
}
};