-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.go
62 lines (52 loc) · 1.06 KB
/
solution.go
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
package smallest_string_with_swaps
import "sort"
func SmallestStringWithSwaps(s string, pairs [][]int) string {
if len(s) < 2 {
return s
}
d := newDisjointSet(len(s))
for _, pair := range pairs {
d.union(pair[0], pair[1])
}
cm := map[int][]int{}
for i := 0; i < len(s); i++ {
key := d.find(i)
if indices, exists := cm[key]; exists {
cm[key] = append(indices, i)
} else {
cm[key] = []int{i}
}
}
buffer := make([]byte, len(s))
for _, indices := range cm {
bytes := make([]byte, len(indices))
for i, index := range indices {
bytes[i] = s[index]
}
sort.Slice(bytes, func(i, j int) bool {
return bytes[i] < bytes[j]
})
for i, index := range indices {
buffer[index] = bytes[i]
}
}
return string(buffer)
}
type disjointSet []int
func newDisjointSet(size int) disjointSet {
items := make([]int, size)
for i := range items {
items[i] = i
}
return items
}
func (d disjointSet) find(x int) int {
if x != d[x] {
d[x] = d.find(d[x])
}
return d[x]
}
func (d disjointSet) union(x, y int) {
x, y = d.find(x), d.find(y)
d[x] = y
}