题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
package main import ( "fmt" "sort" ) type LetterCnt struct { Ch byte Cnt int } func calculate(s string) { m := make(map[byte]int, 0) for i:=0; i<len(s); i++ { m[s[i]]++ } var letters []LetterCnt for k, v := range m { letters = append(letters, LetterCnt{Ch: k, Cnt: v}) } sort.Slice(letters, func(i, j int) bool { if letters[i].Cnt == letters[j].Cnt { return letters[i].Ch < letters[j].Ch } return letters[i].Cnt > letters[j].Cnt }) for _, letter := range letters { fmt.Printf("%c", letter.Ch) } } func main() { var s string fmt.Scan(&s) calculate(s) }
// 本题输入一个字符串,所以采用:fmt.Scan(&s)