/
1202. Smallest String With Swaps.cpp
62 lines (50 loc) · 1.25 KB
/
1202. Smallest String With Swaps.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// https://leetcode.com/problems/smallest-string-with-swaps/
class Solution
{
public:
vector<int> root;
int find(int x)
{
if (root[x] == x)
return x;
return root[x] = find(root[x]);
}
void unionset(int x, int y)
{
int xRoot = find(x);
int yRoot = find(y);
if (xRoot != yRoot)
root[yRoot] = xRoot;
}
string smallestStringWithSwaps(string s, vector<vector<int>> &pairs)
{
int n = s.size();
root.resize(n);
for (int i = 0; i < n; i++)
root[i] = i;
for (auto p : pairs)
unionset(p[0], p[1]);
unordered_map<int, pair<int, string>> z;
for (int i = 0; i < n; i++)
{
int r = find(i);
string ss(1, s[i]);
if (z.find(r) == z.end())
{
z[r] = {-1, ss};
}
else
z[r].second += ss;
}
for (auto &p : z)
sort(p.second.second.begin(), p.second.second.end());
string res = "";
for (int i = 0; i < n; i++)
{
int r = find(i);
int index = ++z[r].first;
res += z[r].second[index];
}
return res;
}
};