-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1202. Smallest String With Swaps.cpp
More file actions
47 lines (38 loc) · 1.27 KB
/
1202. Smallest String With Swaps.cpp
File metadata and controls
47 lines (38 loc) · 1.27 KB
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
class Solution {
public:
// Maximum number of vertices
static const int N = 100001;
vector<int> adj[N];
bool visited[N];
void DFS(string& s, int vertex, vector<char>& chars, vector<int>& indices) {
chars.push_back(s[vertex]);
indices.push_back(vertex);
visited[vertex] = true;
for (int adjacent : adj[vertex]) {
if (!visited[adjacent]) {
DFS(s, adjacent, chars, indices);
}
}
}
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
for (vector<int> edge : pairs) {
int source = edge[0];
int dest = edge[1];
adj[source].push_back(dest);
adj[dest].push_back(source);
}
for (int v = 0; v < s.size(); ++v) {
if (!visited[v]) {
vector<char> chars;
vector<int> indices;
DFS(s, v, chars, indices);
sort(chars.begin(), chars.end());
sort(indices.begin(), indices.end());
for (int i = 0; i < chars.size(); ++i) {
s[indices[i]] = chars[i];
}
}
}
return s;
}
};