1. 程式人生 > 其它 >牛客華為機試HJ19

牛客華為機試HJ19

原題傳送門

1. 題目描述

2. Solution

1、思路
簡單的計數問題,用Hash Table解決即可,本題要求輸出最後8個,先全量統計,最後擷取8個輸出
2、程式碼實現
Java

package huawei.HJ019;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;

public class Main {
    static Scanner in;
    static String inputFileName = "/Users/jun/Documents/Learn/JavaLearning/NowCoder/src/huawei/HJ019/input.txt";

    static {
        if (!"Linux".equals(System.getProperty("os.name"))) {
            try {
                in = new Scanner(Paths.get(inputFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            in = new Scanner(System.in);
        }
    }

    public static void main(String[] args) {
        Map<String, Integer> result = new LinkedHashMap<>();
        while (in.hasNext()) {
            String line = in.nextLine();
            String[] parts = line.split("\\s+");
            String fullName = parts[0];
            String lineNo = parts[1];
            String[] fullNameParts = fullName.split("\\\\");
            String fullNameLastPart = fullNameParts[fullNameParts.length - 1];
            String fileName = fullNameLastPart.substring(Math.max(fullNameLastPart.length() - 16, 0));
            String resKey = String.format("%s %s", fileName, lineNo);
            result.put(resKey, result.getOrDefault(resKey, 0) + 1);
        }

        int cnt = 0;
        for (Map.Entry<String, Integer> entry : result.entrySet()) {
            if (result.size() - cnt <= 8)
                System.out.println(entry.getKey() + " " + entry.getValue());
            cnt++;
        }
    }
}

Python

import sys

if sys.platform != "linux":
    file_in = open("input/HJ19.txt")
    sys.stdin = file_in

result = dict()

for line in sys.stdin:
    full_name, line_no = line.strip().split()
    file_name = full_name.split("\\")[-1][-16:]
    res_key = f'{file_name} {line_no}'
    if res_key not in result:
        result[res_key] = 1
    else:
        result[res_key] += 1

for k, v in list(result.items())[-8:]:
    print(f'{k} {v}')