forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smallest-string-with-swaps.cpp
100 lines (93 loc) · 2.82 KB
/
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
UnionFind union_find(s.length());
for (const auto& pair : pairs) {
union_find.union_set(pair[0], pair[1]);
}
unordered_map<int, vector<char>> components;
for (int i = 0; i < s.length(); ++i) {
components[union_find.find_set(i)].emplace_back(s[i]);
}
for (auto& [i, list] : components) {
sort(list.begin(), list.end(), greater<char>());
}
for (int i = 0; i < s.length(); ++i) {
const auto& j = union_find.find_set(i);
s[i] = components[j].back();
components[j].pop_back();
}
return s;
}
private:
class UnionFind {
public:
UnionFind(const int n) : set_(n) {
iota(set_.begin(), set_.end(), 0);
}
int find_set(const int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
}
bool union_set(const int x, const int y) {
int x_root = find_set(x), y_root = find_set(y);
if (x_root == y_root) {
return false;
}
set_[min(x_root, y_root)] = max(x_root, y_root);
return true;
}
private:
vector<int> set_;
};
};
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
unordered_map<int, vector<int>> adj;
for (const auto& pair : pairs) {
adj[pair[0]].emplace_back(pair[1]);
adj[pair[1]].emplace_back(pair[0]);
}
unordered_set<int> lookup;
string result = s;
for (int i = 0; i < s.length(); ++i) {
if (lookup.count(i)) {
continue;
}
vector<int> component;
dfs(i, adj, &lookup, &component);
sort(component.begin(), component.end());
vector<char> chars;
for (const auto& k : component) {
chars.emplace_back(result[k]);
}
sort(chars.begin(), chars.end());
for (int j = 0; j < component.size(); ++j) {
result[component[j]] = chars[j];
}
}
return result;
}
private:
void dfs(int i, const unordered_map<int, vector<int>>& adj,
unordered_set<int> *lookup, vector<int> *component) {
lookup->emplace(i);
component->emplace_back(i);
if (!adj.count(i)) {
return;
}
for (const auto& j : adj.at(i)) {
if (lookup->count(j)) {
continue;
}
dfs(j, adj, lookup, component);
}
}
};