题解 | #字符统计#

字符统计

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

import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Comparator;
//
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.next();
            System.out.println(getSort(str));
        }
    }

    public static String getSort(String str) {
        String res = "";
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        if (str.length() < 1 || str.length() > 1000) {
            System.out.println("你的输入不合法,请重新输入");
        } else {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            List<Character> cl = new ArrayList<Character>(map.keySet());
            Collections.sort(cl, (Comparator) (o1, 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;
                }
            });
            for (Character ch : cl) {
                res = res + ch;
            }
        }
        return res;
    }
}

全部评论

相关推荐

07-18 15:02
门头沟学院 Java
刚打开网申页面就不想填了,还是不要为难自己了
poppinzhan...:多益老行业毒瘤了,碰到徐波这种恶心的烂人,去了也是受罪。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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