Skip to content

Commit 541d805

Browse files
committed
Time: 5 ms (27.83%), Space: 11.3 MB (18.74%) - LeetHub
1 parent 8d322d1 commit 541d805

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public:
3+
string smallestEquivalentString(string s1, string s2, string baseStr) {
4+
map<char, set<char>> mp;
5+
int n = s1.size();
6+
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+
}
33+
}
34+
for (auto& i : baseStr) {
35+
i = p[i];
36+
}
37+
return baseStr;
38+
}
39+
};

0 commit comments

Comments
 (0)