C++ 见上面,Java 见下面:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashMap<String, Integer> m1 = new HashMap<>();
// 统计每个字符串出现的次数
for (int i = 0; i < n; i++) {
String s = sc.next();
m1.put(s, m1.getOrDefault(s, 0) + 1);
}
TreeMap<Integer, TreeSet<String>> m2 = new TreeMap<>();
// 将字符串按照出现次数分组
for (Map.Entry<String, Integer> entry : m1.entrySet()) {
int key = -entry.getValue(); // 取负值作为键
TreeSet<String> set = m2.computeIfAbsent(key, k -> new TreeSet<>()); // 若不存在则创建
set.add(entry.getKey()); // 添加字符串到 TreeSet
}
// 输出结果
for (Map.Entry<Integer, TreeSet<String>> entry : m2.entrySet()) {
int count = -entry.getKey(); // 计数取负值
for (String s : entry.getValue()) {
System.out.println(s + " " + count);
}
}
}
}