题解 | 字符统计
解题思路:
- 这个是有点偷懒的,直接参考了别人的的答案,使用map的sorted排序
import java.util.HashMap; import java.util.*; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); char[] arr = in.nextLine().toCharArray(); Map<Character, Integer> map = new HashMap<>(); for (char c : arr) { map.put(c, map.getOrDefault(c, 0) + 1); } List<Character> entryList = map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .sorted((o1, o2)->Integer.compare(o2.getValue(), o1.getValue())) .map(Map.Entry::getKey) .collect(Collectors.toList()); entryList.forEach(System.out::print);; } }
其他思路:
1. 使用优先队列
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int[] a = new int[128]; // 统计字符出现次数 for (char c : s.toCharArray()) { a[(int) c]++; } // 使用优先队列按出现次数排序 PriorityQueue<Character> pq = new PriorityQueue<>((c1, c2) -> a[c2] - a[c1]); for (int i = 0; i < a.length; i++) { if (a[i] > 0) { pq.offer((char) i); } } // 输出结果 while (!pq.isEmpty()) { System.out.print(pq.poll()); } } }
}