Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Feb 7, 2024
1 parent f0e5486 commit f8f156f
Showing 1 changed file with 57 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// https://leetcode.com/problems/sort-characters-by-frequency

package main

import (
"bytes"
"fmt"
"sort"
)

func frequencySort(s string) string {

// count character
cnt := map[byte]int{}
for i := range s {
cnt[s[i]]++
}

// sort character
cs := make([]byte, 0, len(s))
for c := range cnt {
cs = append(cs, c)
fmt.Println(cs)
}
sort.Slice(cs, func(i, j int) bool { return cnt[cs[i]] > cnt[cs[j]] })
fmt.Println(cs)

for _, s := range cs {
tmp := sortString(string(s))
fmt.Println(tmp)
}

// append to res
res := make([]byte, 0, len(s))
for _, c := range cs {
res = append(res, bytes.Repeat([]byte{c}, cnt[c])...)
}
return string(res)
}

func sortString(s string) string {
bytes := []byte(s)
tmp := make([]int, len(bytes))
for i, b := range bytes {
tmp[i] = int(b)
}
sort.Ints(tmp)
for i, v := range tmp {
bytes[i] = byte(v)
}
return string(bytes)
}

func main() {
s := "aaabccc"
fmt.Println(frequencySort(s))
}

0 comments on commit f8f156f

Please sign in to comment.