题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.*; public class Main { public static void main(String[] args) { Scanner fzhinput = new Scanner(System.in); String zfc = fzhinput.nextLine(); LinkedHashMap<Character,Integer> zd = new LinkedHashMap<>(); for (char ch : zfc.toCharArray()) { zd.put(ch, zd.getOrDefault(ch, 0) + 1); } // 将Map中的键提取到列表中,并按频率降序和ASCII码升序排序 List<Character> characters = new ArrayList<>(zd.keySet()); characters.sort((a, b) -> { int freqCompare = zd.get(b) - zd.get(a); // 按频率降序排序 if (freqCompare != 0) { return freqCompare; } else { return a - b; // 如果频率相同,按ASCII码升序排序 } }); StringBuilder result = new StringBuilder(); for (char c : characters) { result.append(c); } System.out.println(result.toString()); } }