Skip to content

Commit 7aa29e5

Browse files
authored
Create lexicographically-smallest-equivalent-string.cpp
1 parent 0955cdb commit 7aa29e5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Time: O(nlog*n) ~= O(n), n is the length of S
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
string smallestEquivalentString(string A, string B, string S) {
7+
UnionFind union_find(26);
8+
for (int i = 0; i < A.length(); ++i) {
9+
union_find.union_set(A[i] - 'a', B[i] - 'a');
10+
}
11+
string result;
12+
for (int i = 0; i < S.length(); ++i) {
13+
const auto& parent = union_find.find_set(S[i] - 'a');
14+
result.push_back(parent + 'a');
15+
}
16+
return result;
17+
}
18+
19+
private:
20+
class UnionFind {
21+
public:
22+
UnionFind(const int n) : set_(n) {
23+
iota(set_.begin(), set_.end(), 0);
24+
}
25+
26+
int find_set(const int x) {
27+
if (set_[x] != x) {
28+
set_[x] = find_set(set_[x]); // Path compression.
29+
}
30+
return set_[x];
31+
}
32+
33+
void union_set(const int x, const int y) {
34+
int x_root = find_set(x), y_root = find_set(y);
35+
if (x_root != y_root) {
36+
set_[max(x_root, y_root)] = min(x_root, y_root);
37+
}
38+
}
39+
40+
private:
41+
vector<int> set_;
42+
};
43+
};

0 commit comments

Comments
 (0)