题解 | #字符统计#

字符统计

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

劝退写法:利用map存储字符以及次数,再用Collections.sort()进行排序,排序需要把map转换成list。

public class Main{
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()){
           String str = sc.nextLine();
           Map<Character,Integer> map = new HashMap<>();
            for(int i = 0 ;i<str.length();++i){
               if(map.containsKey(str.charAt(i))){
                   map.put(str.charAt(i),map.get(str.charAt(i))+1);
               }
               else {
                   map.put(str.charAt(i),1);
               }
           }
            List<Map.Entry<Character,Integer>> list = new ArrayList<>(map.entrySet());
            Collections.sort(list,new Comparator<Map.Entry<Character,Integer>>(){
                public  int compare(Map.Entry<Character,Integer> k1,Map.Entry<Character,Integer> k2){
                    if(k1.getValue()==k2.getValue()){
                        return k1.getKey()-k2.getKey();
                    }else return k2.getValue()-k1.getValue();
                }
            });
            for(Map.Entry<Character,Integer> entry:list){
                System.out.print(entry.getKey());
            }
             System.out.println();
        }
        
    }
}
全部评论

相关推荐

01-15 13:45
门头沟学院 Java
牛客92772631...:boss招聘挂岗位是要花钱的,花了钱不挂白不挂,别那么焦虑,但是也要做好跳槽的准备
找实习记录
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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