题解 | #字符统计#

字符统计

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

import java.util.*;
import java.util.Map.Entry;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String text = sc.next();
        Map<Character, Integer> map = new HashMap<>();
        Comparator<Character> comparator = (c1, c2) -> {
            if (map.get(c1).equals(map.get(c2))) {
                return c1 - c2;
            } else {
                return map.get(c2) - map.get(c1);
            }
        };
        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            map.merge(ch, 1, (oldVal, newVal) -> oldVal + 1);
        }
        Map<Character, Integer> treeMap = new TreeMap<>(comparator);
        treeMap.putAll(map);
        for (Entry<Character, Integer> entry : treeMap.entrySet()) {
            System.out.print(entry.getKey());
        }
    }
}

全部评论

相关推荐

xwqlikepsl:感觉很厉害啊,慢慢找
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务