题目
HJ102 字符统计
golang代码实现
package main
import (
"bufio"
"fmt"
"os"
"sort"
)
func main() {
// str_arry :=make([]string, 0)
str_map := make(map[rune]int)
result_map := make(map[int][]string)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
str := scanner.Text()
for _, r := range str {
_, ok := str_map[r]
if ok {
//删除
srt_tmp := result_map[str_map[r]]
for i, s_tmp := range srt_tmp {
if s_tmp == string(r) {
if i < len(srt_tmp)-1 {
srt_tmp = append(srt_tmp[:i], srt_tmp[i+1:]...)
} else {
srt_tmp = srt_tmp[:i]
}
}
}
result_map[str_map[r]] = srt_tmp
str_map[r] += 1
//新增到指定数组中
result_map[str_map[r]] = append(result_map[str_map[r]], string(r))
} else {
str_map[r] = 1
result_map[1] = append(result_map[1], string(r))
}
}
}
lenstr:=len(result_map)
for i:=lenstr;i>=1;i--{
arr :=result_map[i]
if len(arr)>0{
sort.Sort(byASCII(arr))
for _,v:=range arr{
fmt.Printf("%s", v)
}
}
}
}
type byASCII []string
func (s byASCII) Len() int {
return len(s)
}
func (s byASCII) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byASCII) Less(i, j int) bool {
for k := 0; k < len(s[i]) && k < len(s[j]); k++ {
if s[i][k] != s[j][k] {
return s[i][k] < s[j][k]
}
}
return len(s[i]) < len(s[j])
}