-
Notifications
You must be signed in to change notification settings - Fork 112
/
1061-LexicographicallySmallestEquivalentString.cs
57 lines (48 loc) · 1.64 KB
/
1061-LexicographicallySmallestEquivalentString.cs
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
//-----------------------------------------------------------------------------
// Runtime: 120ms
// Memory Usage: 23.6 MB
// Link: https://leetcode.com/submissions/detail/364037143/
//-----------------------------------------------------------------------------
using System.Text;
namespace LeetCode
{
public class _1061_LexicographicallySmallestEquivalentString
{
public string SmallestEquivalentString(string A, string B, string S)
{
var uf = new UnionFind(26);
for (int i = 0; i < A.Length; i++)
uf.Union(A[i] - 'a', B[i] - 'a');
var sb = new StringBuilder(S.Length);
foreach (var ch in S)
sb.Append((char)(uf.Find(ch - 'a') + 'a'));
return sb.ToString();
}
private class UnionFind
{
private readonly int[] parents;
public UnionFind(int count)
{
this.parents = new int[count];
for (int i = 0; i < count; i++)
parents[i] = i;
}
public int Find(int index)
{
if (parents[index] != index)
parents[index] = Find(parents[index]);
return parents[index];
}
public void Union(int index1, int index2)
{
var pIndex1 = Find(index1);
var pIndex2 = Find(index2);
if (pIndex1 == pIndex2) return;
if (pIndex1 < pIndex2)
parents[pIndex2] = pIndex1;
else
parents[pIndex1] = pIndex2;
}
}
}
}