-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_arrange.go
72 lines (60 loc) · 1.79 KB
/
string_arrange.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
63
64
65
66
67
68
69
70
71
72
/*
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
*/
package main
import (
"fmt"
"sort"
)
type CharOccurance struct {
char rune
count int
}
func rearrangeCharacters(s string) string {
charCountMap := make(map[rune]int)
var counts []CharOccurance
// find out the count of each character
for _, char := range s {
charCountMap[char]++
}
for char, count := range charCountMap {
counts = append(counts, CharOccurance{char, count})
}
sort.Slice(counts, func(i, j int) bool {
return counts[i].count > counts[j].count
})
var result []rune
for len(result) < len(s) {
// if first character in counts not same as the current character in result, appending the character to result
if len(result) == 0 || result[len(result)-1] != counts[0].char {
result = append(result, counts[0].char)
// decreasing the character count as we already append it to result
counts[0].count--
} else {
// If counts have only one character or the next character have 0 count, return empty string
if len(counts) < 2 || counts[1].count == 0 {
return ""
}
// appending the next character to result and decreasing it's count
result = append(result, counts[1].char)
counts[1].count--
}
// sort the counts slice with latest character count values
sort.Slice(counts, func(i, j int) bool {
return counts[i].count > counts[j].count
})
}
return string(result)
}
func main() {
fmt.Println(rearrangeCharacters("acbdba")) // Output: "babacd"
fmt.Println(rearrangeCharacters("acbdbacccefgk")) // Output: "cacbcbcadefgk"
fmt.Println(rearrangeCharacters("aaaba")) // Output: ""
}