题解 | #简单错误记录#

简单错误记录

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());
            }
        }
    }
}

全部评论

相关推荐

09-22 15:45
门头沟学院 Java
谁给娃offer我给...:我也遇到了,我说只要我通过面试我就去,实际上我根本就不会去😁
点赞 评论 收藏
分享
算法丰川祥:实际就两个人给他投,它这么说好显得自己比较抢手
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务