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
65
66
|
type UnionFind struct {
parent []int
rank []int
posArr [][]int
}
func NewUnionFind(n int) *UnionFind {
uf := &UnionFind{parent: make([]int, n), rank: make([]int, n), posArr: make([][]int, n)}
for i := 0; i < n; i++ {
uf.parent[i] = i
uf.rank[i] = 1
uf.posArr[i] = append(uf.posArr[i], i)
}
return uf
}
func (uf *UnionFind) Find(i int) int {
if uf.parent[i] != i {
uf.parent[i] = uf.Find(uf.parent[i])
}
return uf.parent[i]
}
func (uf *UnionFind) Merge(i, j int) {
iF, jF := uf.Find(i), uf.Find(j)
if iF != jF {
if uf.rank[iF] <= uf.rank[jF] {
uf.parent[iF] = jF
uf.posArr[jF] = append(uf.posArr[jF], uf.posArr[iF]...)
} else {
uf.parent[jF] = iF
uf.posArr[iF] = append(uf.posArr[iF], uf.posArr[jF]...)
}
if uf.rank[iF] == uf.rank[jF] {
uf.rank[jF]++
}
}
}
func (uf *UnionFind) Resolve(str string) string {
buf := make([]byte, len(str))
for k, v := range uf.parent {
if k == v {
posArr := uf.posArr[k]
t := append([]int(nil), posArr...)
sort.Ints(posArr)
sort.Slice(t, func(i, j int) bool {
return str[t[i]] < str[t[j]]
})
for i, pos := range posArr {
buf[pos] = str[t[i]]
}
}
}
return string(buf)
}
func smallestStringWithSwaps(s string, pairs [][]int) string {
n := len(s)
uf := NewUnionFind(n)
for _, pair := range pairs {
u, v := pair[0], pair[1]
uf.Merge(u, v)
}
return uf.Resolve(s)
}
|