题解 | #字符统计#

字符统计

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

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String str = sc.nextLine();
            HashMap<Character, Integer> map = new HashMap<>();
            //把 字符-出现次数 放入HashMap中
            for (char ch : str.toCharArray()) {
                map.put(ch, map.getOrDefault(ch, 0) + 1);
            }
            //再把字符放入ArrayList中,自定义比较器进行sort
            List<Character> chList = new ArrayList<>(map.keySet());
            Collections.sort(chList, new Comparator() {
                public int compare(Object o1, Object o2) {
                    Character ch1 = (Character) o1;
                    Character ch2 = (Character) o2;
                    if (map.get(ch1) > map.get(ch2)) {//先按照字符出现次数排列,次数高的排前面
                        return -1;
                    } else if (map.get(ch1) < map.get(ch2)) {
                        return 1;
                    } else {
                        return ch1 - ch2;//按照字符ASCII顺序升序排列。此处自动拆箱为char再自动转型为int
                    }
                }
            });
            //输出排序后的字符
            for (Character ch : chList) {
                System.out.print(ch.toString());
            }
            System.out.println();
        }
    }
}
全部评论
为啥arraylist可以直接将set集合作为构造器参数
点赞 回复 分享
发布于 2023-05-06 11:24 广东

相关推荐

评论
8
1
分享

创作者周榜

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