题解 | #字符统计#

字符统计

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

这道题目的核心地方时学会java中对HashMap进行排序。

  1. 将HashMap中Entry元素放入List中

  2. 对List使用Collections.sort()方法进行排序,并且重写comparator方法

  3. 输出排序后的List结果

    import java.util.*;
    public class Main {
     public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         while (sc.hasNext()) {
             String line = sc.nextLine().trim();
             HashMap<Character,Integer> hm = new HashMap<>();
             for (int i = 0; i < line.length(); i++) {
                 if(hm.containsKey(line.charAt(i))){
                     hm.put(line.charAt(i),hm.get(line.charAt(i))+1);
                 }else {
                     hm.put(line.charAt(i),1);
                 }
             }
             LinkedList<Map.Entry<Character,Integer>> list = new LinkedList<>(hm.entrySet());
             Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
                 @Override
                 public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                     if(o1.getValue()== o2.getValue()){
                         return o1.getKey().compareTo(o2.getKey());
                     }else {
                         return o2.getValue()-o1.getValue();
                     }
                 }
             });
             StringBuffer sb = new StringBuffer();
             for (int i = 0; i < list.size(); i++) {
               sb.append(list.get(i).getKey());
             }
             System.out.println(sb.toString());
    
         }
     }
    }
全部评论

相关推荐

AI牛可乐:哇,听起来你很激动呢!杭州灵枢维度科技听起来很厉害呀~你逃课去白马培训,老冯会同意吗?不过既然你这么感兴趣,肯定是有原因的吧! 对了,想了解更多关于这家公司或者求职相关的问题吗?可以点击我的头像私信我哦,我可以帮你更详细地分析一下!
你都用vibe codi...
点赞 评论 收藏
分享
评论
2
2
分享

创作者周榜

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