Skip to content

Commit ba4a82c

Browse files
authored
Create L767.go
1 parent cbfde68 commit ba4a82c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Medium/L767.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package Medium
2+
3+
type Pair struct {
4+
Key byte
5+
Value int
6+
}
7+
8+
type PairList []Pair
9+
10+
func (p PairList) Len() int { return len(p) }
11+
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
12+
func (p PairList) Less(i, j int) bool { return p[i].Value > p[j].Value }
13+
14+
func reorganizeString(s string) string {
15+
freqMap, res := make(map[byte]int), make([]byte, len(s))
16+
for _, ch := range s {
17+
freqMap[byte(ch)]++
18+
}
19+
20+
getSortedChars := func() PairList {
21+
p := make(PairList, len(freqMap))
22+
i := 0
23+
for k, v := range freqMap {
24+
p[i] = Pair{
25+
Key: k,
26+
Value: v,
27+
}
28+
i++
29+
}
30+
sort.Sort(p)
31+
32+
return p
33+
}
34+
35+
sortedChars := getSortedChars()
36+
if freqMap[sortedChars[0].Key] > ((len(s) + 1) / 2) {
37+
return ""
38+
}
39+
40+
idx := 0
41+
for _, pair := range sortedChars {
42+
for j := 0; j < freqMap[pair.Key]; j++ {
43+
if idx >= len(s) {
44+
idx = 1
45+
}
46+
res[idx] = pair.Key
47+
idx += 2
48+
}
49+
}
50+
return string(res)
51+
}

0 commit comments

Comments
 (0)