题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); HashMap<String, Integer> treeMap = new HashMap<>(); char[] arr = str.toCharArray(); // 遍历所有字符,并且放到map中.key是字符,value是出现次数. for (int i = 0; i < arr.length; i++) { treeMap.put(String.valueOf(arr[i]), treeMap.getOrDefault(String.valueOf(arr[i]), 0) + 1); } ArrayList<Map.Entry<String, Integer>> list = new ArrayList<> (treeMap.entrySet()); // 排序 Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { if (o1.getValue().compareTo(o2.getValue()) == 0) { // 次数相同,按照key升序 return o1.getKey().compareTo(o2.getKey()); } else { // 降序 return o2.getValue().compareTo(o1.getValue()); } } }); for (Map.Entry<String, Integer> mapping : list) { System.out.print(mapping.getKey()); } } }