题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.*; import java.util.Map.Entry; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String text = sc.next(); Map<Character, Integer> map = new HashMap<>(); Comparator<Character> comparator = (c1, c2) -> { if (map.get(c1).equals(map.get(c2))) { return c1 - c2; } else { return map.get(c2) - map.get(c1); } }; for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); map.merge(ch, 1, (oldVal, newVal) -> oldVal + 1); } Map<Character, Integer> treeMap = new TreeMap<>(comparator); treeMap.putAll(map); for (Entry<Character, Integer> entry : treeMap.entrySet()) { System.out.print(entry.getKey()); } } }