题解 | #字符统计#

字符统计

https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
//对于Arrays.sort(int[] var0)使用的是快排,所以是不稳定的.
//对于Collections.sort(List elements)使用的是归并排序,是稳定的
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        Map<Character, Integer> treemap = new TreeMap<>();
        String s = in.nextLine();

        for(int i=0 ; i<s.length() ; ++i){
            treemap.put(s.charAt(i), treemap.getOrDefault(s.charAt(i), 0)+1);
        }
        List<Map.Entry<Character, Integer>> list = new ArrayList<>(treemap.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>(){
            public int compare(Map.Entry<Character, Integer> m1, Map.Entry<Character, Integer> m2){
                return (m2.getValue()-m1.getValue());
            }
        });
        for(int i=0 ; i<list.size() ; ++i){
            System.out.print(list.get(i).getKey());
        }




    }
}

全部评论

相关推荐

牛客83265014...:完了,连现在都没开始面,13号投的是不是晚了
秋招的第一个offer,...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务