Skip to content

Commit 922b3f8

Browse files
committed
Time: 0 ms (100%), Space: 8.6 MB (96.66%) - LeetHub
1 parent 541d805 commit 922b3f8

File tree

1 file changed

+25
-28
lines changed

1 file changed

+25
-28
lines changed

1061-lexicographically-smallest-equivalent-string/1061-lexicographically-smallest-equivalent-string.cpp

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,35 @@
1+
class DSU {
2+
public:
3+
vector<int> parent;
4+
DSU(int n) {
5+
parent.resize(n + 5);
6+
iota(parent.begin(), parent.end(), 0);
7+
}
8+
9+
int root(int x) {
10+
return(parent[x] == x ? x : parent[x] = root(parent[x]));
11+
}
12+
13+
void join(int x, int y) {
14+
x = root(x);
15+
y = root(y);
16+
if (x < y) parent[y] = x;
17+
else parent[x] = y;
18+
return;
19+
}
20+
21+
};
22+
123
class Solution {
224
public:
325
string smallestEquivalentString(string s1, string s2, string baseStr) {
4-
map<char, set<char>> mp;
526
int n = s1.size();
27+
DSU dsu(26);
628
for (int i = 0; i < n; i++) {
7-
mp[s1[i]].insert(s2[i]);
8-
mp[s2[i]].insert(s1[i]);
9-
}
10-
map<char, bool> vis;
11-
set<char> temp;
12-
function<void(char)> dfs = [&](char c) {
13-
temp.insert(c);
14-
vis[c] = true;
15-
for (auto& j : mp[c]) {
16-
if (!vis[j]) {
17-
dfs(j);
18-
}
19-
}
20-
};
21-
map<char, char> p;
22-
for (char c = 'a'; c <= 'z'; c++) {
23-
if (!vis[c]) {
24-
temp.clear();
25-
dfs(c);
26-
int x = *temp.begin();
27-
temp.erase(temp.begin());
28-
p[x] = x;
29-
for (auto& i : temp) {
30-
p[i] = x;
31-
}
32-
}
29+
dsu.join(s1[i] - 'a', s2[i] - 'a');
3330
}
3431
for (auto& i : baseStr) {
35-
i = p[i];
32+
i = char(dsu.root(i - 'a') + 'a');
3633
}
3734
return baseStr;
3835
}

0 commit comments

Comments
 (0)