Skip to content

Commit 11bc569

Browse files
authored
Create 1722.Minimize-Hamming-Distance-After-Swap-Operations.cpp
1 parent 23d4d48 commit 11bc569

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution {
2+
vector<int>Father;
3+
public:
4+
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
5+
int N = s.size();
6+
Father.resize(N);
7+
for (int i=0; i<N; i++)
8+
Father[i] = i;
9+
10+
for (auto& p :pairs)
11+
{
12+
int a = p[0];
13+
int b = p[1];
14+
if (FindFather(a)!=FindFather(b))
15+
Union(a,b);
16+
}
17+
18+
unordered_map<int, vector<int>>Map; // root idx -> all indexes
19+
for (int i=0; i<N; i++)
20+
{
21+
Map[FindFather(i)].push_back(i);
22+
}
23+
24+
for (auto x: Map)
25+
{
26+
string temp;
27+
for (auto idx : x.second)
28+
temp.push_back(s[idx]);
29+
sort(temp.begin(),temp.end());
30+
int k = 0;
31+
for (auto idx : x.second)
32+
{
33+
s[idx] = temp[k];
34+
k++;
35+
}
36+
}
37+
38+
return s;
39+
}
40+
41+
int FindFather(int x)
42+
{
43+
if (Father[x]!=x)
44+
Father[x] = FindFather(Father[x]);
45+
return Father[x];
46+
}
47+
48+
void Union(int x, int y)
49+
{
50+
x = Father[x];
51+
y = Father[y];
52+
if (x<y)
53+
Father[y] = x;
54+
else
55+
Father[x] = y;
56+
}
57+
};

0 commit comments

Comments
 (0)