题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
private static String s = "";
private static Map<Character, Integer> count = new HashMap<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
s = in.next();
}
initMap();
List<Node1> nodeList = initNode();
nodeList.sort(Comparator.comparing(Node1::getCCount).reversed()
.thenComparing(i -> i.c)
);
nodeList.forEach(i -> {
System.out.print(i.c);
});
}
private static void initMap() {
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
count.put(c, count.getOrDefault(c, 0) + 1);
}
}
private static List<Node1> initNode() {
List<Node1> list = new LinkedList<>();
count.forEach((k, v) -> {
Node1 n = new Node1();
n.c = k.charValue();
n.cCount = v;
list.add(n);
});
return list;
}
static class Node1 {
public int cCount = 0;
public char c;
public int getCCount(){
return cCount;
}
}
}
雪域灰灰刷题笔记 文章被收录于专栏
雪域灰灰刷题笔记
查看9道真题和解析