题解 | #字符统计#

字符统计

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

自定义排序
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        HashMap<Character, Integer> map = new HashMap<>();
        for (char c : input.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        ArrayList<Map.Entry<Character,Integer>> list = new ArrayList<>();
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            list.add(entry);
        }
        list.sort((o1, o2) -> (o1.getValue() == o2.getValue() ? o1.getKey() - o2.getKey() : o2.getValue() - o1.getValue()));
        for (Map.Entry<Character, Integer> entry : list) {
            System.out.print(entry.getKey());
        }
    }
}




全部评论

相关推荐

只写bug的程序媛:才15,我招行20多万,建设银行50多万,说放弃就放弃
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务