华为机考-编程

输入字符串
求出字符串里的不同字符的个数,并按照字符数的大小输出
若字符数相同则按自然排序
例如:
输入:aaabbcc
输出:3:a;2:c:2:b



import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        if(scanner.hasNextLine()) {
            char[] arr;
            arr = scanner.nextLine().toCharArray();
            TreeMap<Character, Integer> treeMap = new TreeMap<Character, Integer>();

            for (int i = 0; i < arr.length; i++) {
                if(treeMap.containsKey(arr[i]))
                {
                    treeMap.put(arr[i],treeMap.get(arr[i])+1);

                }else {
                    treeMap.put(arr[i], 1);

                }
            }

            List<String> list=new ArrayList<>();
            for(Map.Entry<Character, Integer> entry:treeMap.entrySet())
            {
               list.add(entry.getValue()+":"+entry.getKey());

            }
            Collections.sort(list);
            Collections.reverse(list);
            for(String s:list)
            {
                String temp = s;
                System.out.print(temp+";");

            }

        }
    }


}

你可能感兴趣的:(笔记)