File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
Union_Find/1722.Minimize-Hamming-Distance-After-Swap-Operations Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments