题解 | #简单错误记录#
简单错误记录
https://www.nowcoder.com/practice/2baa6aba39214d6ea91a2e03dff3fbeb
要对每个错误计数,这里想到用Map,要取后8个,说明Map要有序。所以选择LinkedHashMap。
最后遍历后八个元素时,使用迭代器,前面的元素过滤掉。
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 创建有序的map集合
LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
String[] arrStr = str.split("\\\\");
String s = arrStr[arrStr.length - 1];
String[] arrStr2 = s.split(" ");
if (arrStr2[0].length() > 16) {
s = arrStr2[0].substring(arrStr2[0].length() - 16) + " " + arrStr2[1];
}
if (lhm.keySet().contains(s)) {
lhm.put(s, lhm.get(s) + 1);
} else {
lhm.put(s, 1);
}
}
if (lhm.size() > 8) {
Iterator entries = lhm.entrySet().iterator();
Map.Entry en = null;
// 迭代器,把前面的过滤掉,留下最后八位。
for (int i = 0; i < lhm.size(); i++) {
if (i < lhm.size() - 8) {
// 前面的数据不打印,但指针是移动的
en = (Map.Entry) entries.next();
} else {
en = (Map.Entry) entries.next();
System.out.println(en.getKey() + " " + en.getValue());
}
}
} else {
Iterator entries = lhm.entrySet().iterator();
Map.Entry en = null;
while (entries.hasNext()) {
en = (Map.Entry) entries.next();
System.out.println(en.getKey() + " " + en.getValue());
}
}
}
}

