-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1202SmallestStringWithSwaps.cpp
More file actions
36 lines (34 loc) · 982 Bytes
/
1202SmallestStringWithSwaps.cpp
File metadata and controls
36 lines (34 loc) · 982 Bytes
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
32
33
34
35
36
//
// Created by Alaric on 2019-09-30.
//
class Solution {
public:
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
vector<vector<int>> g(s.length());
for (const auto& e : pairs) {
g[e[0]].push_back(e[1]);
g[e[1]].push_back(e[0]);
}
unordered_set<int> seen;
vector<int> idx;
string tmp;
function<void(int)> dfs = [&](int cur) {
if (seen.count(cur)) return;
seen.insert(cur);
idx.push_back(cur);
tmp += s[cur];
for (int nxt : g[cur]) dfs(nxt);
};
for (int i = 0; i < s.length(); ++i) {
if (seen.count(i)) continue;
idx.clear();
tmp.clear();
dfs(i);
sort(begin(tmp), end(tmp));
sort(begin(idx), end(idx));
for (int k = 0; k < idx.size(); ++k)
s[idx[k]] = tmp[k];
}
return s;
}
};