-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
64 lines (58 loc) · 1.35 KB
/
Solution.cs
File metadata and controls
64 lines (58 loc) · 1.35 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
59
60
61
62
63
64
public class Solution
{
public string SmallestEquivalentString(string s1, string s2, string baseStr)
{
int n = s1.Length;
UnionFind uf = new(26);
for (int i = 0; i < n; i++)
{
int a = s1[i] - 'a';
int b = s2[i] - 'a';
uf.Union(a, b);
}
StringBuilder sb = new();
foreach (char c in baseStr)
{
int root = uf.Find(c - 'a');
sb.Append((char)(root + 'a'));
}
return sb.ToString();
}
}
public class UnionFind
{
private readonly int[] parent;
private readonly int[] rank;
public UnionFind(int n)
{
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++)
{
parent[i] = i;
rank[i] = -i;
}
}
public bool Union(int x, int y)
{
int rootX = Find(x);
int rootY = Find(y);
if (rootX == rootY) return false;
if (rank[rootX] <= rank[rootY])
{
parent[rootX] = rootY;
// rank[rootY]++;
}
else if (rank[rootX] > rank[rootY])
{
parent[rootY] = rootX;
// rank[rootX]++;
}
return true;
}
public int Find(int x)
{
if (parent[x] == x) return x;
return parent[x] = Find(parent[x]);
}
}