-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lexicographically_Smalles_Equivalent_Stringt_
54 lines (39 loc) · 1.27 KB
/
Lexicographically_Smalles_Equivalent_Stringt_
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
class Solution {
public:
string smallestEquivalentString(string s1, string s2, string baseStr) {
char ch[26];
for (int i=0; i<26; i++)
ch[i] = 'a' + i;
for (int i=0; i<s1.size(); i++) {
char toReplace = max(ch[s1[i]-'a'], ch[s2[i]-'a']);
char replaceWith = min(ch[s1[i]-'a'], ch[s2[i]-'a']);
for (int i=0; i<26; i++)
if (ch[i] == toReplace)
ch[i] = replaceWith;
}
for (int i = 0; i<baseStr.size(); i++)
baseStr[i] = ch[baseStr[i]-'a'];
return baseStr;
}
/*class Solution {
public:
int par[26];
}; int find(int x){
if(par[x]==-1) return x;
return par[x]=find(par[x]);
}
void Union(int x, int y) {
x = find(x);
y = find(y);
if (x != y)
par[max(x, y)] = min(x, y);
}
string smallestEquivalentString(string s1, string s2, string baseStr) {
memset(par, -1, sizeof(par));
for (auto i = 0; i < s1.size(); ++i)
Union(s1[i] - 'a', s2[i] - 'a');
for(auto i=0;i<baseStr.size();i++)
baseStr[i]=find(baseStr[i]-'a')+'a';
return baseStr;
}
};