File tree 1 file changed +13
-12
lines changed
scripts/algorithms/S/Smallest String With Swaps
1 file changed +13
-12
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 370 ms (Top 35.98%) | Memory: 87.5 MB (Top 5.47%)
1
2
class Solution {
2
3
public:
3
-
4
+
4
5
vector<int > parent;
5
-
6
+
6
7
int findParent (int n)
7
8
{
8
9
if (parent[n] == n) return n;
9
10
return parent[n] = findParent (parent[n]);
10
11
}
11
-
12
+
12
13
string smallestStringWithSwaps (string s, vector<vector<int >>& pairs)
13
14
{
14
15
map<int , set<int >> mp;
15
16
parent.resize (s.size ());
16
17
string ans = s;
17
-
18
+
18
19
for (int i=0 ; i<s.length (); i++) parent[i] = i;
19
-
20
+
20
21
for (auto pair: pairs)
21
22
{
22
23
int p1 = findParent (pair[0 ]), p2 = findParent (pair[1 ]);
23
24
if (p1 != p2) parent[p2] = p1;
24
25
}
25
-
26
+
26
27
for (auto pair: pairs)
27
28
{
28
29
int p = findParent (pair[0 ]);
29
30
mp[p].insert (pair[0 ]);
30
31
mp[p].insert (pair[1 ]);
31
32
}
32
-
33
+
33
34
for (auto it: mp)
34
35
{
35
36
vector<char > part;
36
37
set<int > idx = it.second ;
37
-
38
+
38
39
for (auto index : idx) part.push_back (s[index ]);
39
-
40
+
40
41
sort (part.begin (), part.end ());
41
-
42
+
42
43
auto index = idx.begin ();
43
- for (auto x: part) ans[*index ] = x, ++index ;
44
+ for (auto x: part) ans[*index ] = x, ++index ;
44
45
}
45
46
46
47
return ans;
47
48
}
48
- };
49
+ };
You can’t perform that action at this time.
0 commit comments