题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.Scanner; import java.util.HashMap; import java.util.Collections; import java.util.ArrayList; import java.util.Comparator; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String str = sc.nextLine(); HashMap<Character, Integer> map = new HashMap<>(); //把 字符-出现次数 放入HashMap中 for (char ch : str.toCharArray()) { map.put(ch, map.getOrDefault(ch, 0) + 1); } // 再把字符放入ArrayList中,自定义比较器进行sort ArrayList<Character> chList = new ArrayList<>(map.keySet()); Collections.sort(chList, new Comparator<Character>() { public int compare(Character c1, Character c2) { int num = map.get(c2)-map.get(c1); int num2 = num==0?c1 - c2:num; return num2; } }); //输出排序后的字符 for (Character ch : chList) { System.out.print(ch.toString()); } System.out.println(); } sc.close(); } }