题解 | #字符统计#

字符统计

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();//接受字符串
        TreeMap<Character,Integer> tm = new TreeMap<>();//统计字符种类和个数,同时按照字典排序

        for(int i=0;i<str.length();i++){ //收入集合
            char ch = str.charAt(i);
            if(tm.containsKey(ch)){
                int value = tm.get(ch);
                tm.put(ch,++value);
            
            }else{
                tm.put(ch,1);
            }
        }

        ArrayList<Integer> arr = new  ArrayList<>();//统计字符数量情况
        for(Character k:tm.keySet()){
            arr.add(tm.get(k));
        }
	  
        arr.sort(Integer::compareTo);//按数量从小到大排列
        String aim = "";
	  
        for(int i=0;i<arr.size();i++){
            for(Character k:tm.keySet()){
                if(tm.get(k) == arr.get(arr.size()-i-1)){//按字符数量从大到小合并到aim字符串上
                    aim += k;
                    tm.remove(k,tm.get(k));//删除字符
                    break;
                }
            }
        }

        System.out.println(aim);//输出

    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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