-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1061-lexicographically-smallest-equivalent-string.cpp
More file actions
58 lines (53 loc) · 1.46 KB
/
1061-lexicographically-smallest-equivalent-string.cpp
File metadata and controls
58 lines (53 loc) · 1.46 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
48
49
50
51
52
53
54
55
56
57
58
class Solution {
struct dsu {
vector<int> parent;
vector<int> size_;
vector<char> min_element;
dsu(int n) {
parent = vector<int>(n);
for (int i = 0; i < n; i++) parent[i] = i;
size_ = vector<int>(n, 1);
min_element = vector<char>(n);
for (int i = 'a'; i <= 'z'; i++) min_element[i - 'a'] = i;
}
int find_(int x) {
int root = x;
while (root != parent[root]) {
root = parent[root];
}
//Path compression
while (parent[x] != root) {
int p = parent[x];
parent[x] = root;
x = p;
}
return root;
}
bool union_(int x,int y) {
int X = find_(x);
int Y = find_(y);
// x and y are already in the same set
if (X == Y) return false;
// x and y are not in same set, so we merge them
if (size_[X] < size_[Y]) swap(X, Y);
// merge yRoot into xRoot
parent[Y] = X;
size_[X] += size_[Y];
min_element[X] = min(min_element[X], min_element[Y]);
return true;
}
};
public:
string smallestEquivalentString(string s1, string s2, string baseStr) {
dsu ds(26);
for (int i = 0; i < s1.size(); i++) {
ds.union_(s1[i] - 'a', s2[i] - 'a');
}
string ans;
for (auto c: baseStr) {
int cp = ds.find_(c - 'a');
ans += ds.min_element[cp];
}
return ans;
}
};