10、考勤信息——华子机试必知必会

318 阅读1分钟

题目描述

公司用一个字符串来表示员工的出勤信息

  • absent: 缺勤
  • late: 迟到
  • leaveearly: 早退
  • present: 正常上班.

现需根据员工出勤信息,判断本次是否能获得出勤奖,能获得出勤奖的条件如下

  • 缺勤不超过一次
  • 没有连续的迟到/早退,
  • 任意连续 7 次考勤,缺勤/迟到/早退不超过 3 次

输入描述

用户的考勤数据字符串

记录条数 >= 1;

输入字符串长度< 10000:

不存在非法输入;

如:

present
present absent present present leaveearly present absent

输出描述

根据考勤数据字符串,如果能得到考勤奖,输出”true”;否则输出”false”对于输入示例的结果应为:

true或者false

题解

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入记录条数:");
        int num = Integer.parseInt(sc.nextLine());

        for (int i = 0; i < num; i++) {
            System.out.println("请输入第" + (i + 1) + "条考勤记录:");
            String input = sc.nextLine();
            boolean result = isEligibleForAward(input);
            System.out.println(result ? "true" : "false");
        }
    }

    /**
     * 是否能获得出勤奖
     * @param attendanceData
     * @return
     */
    public static boolean isEligibleForAward(String attendanceData) {
        String[] infos = attendanceData.split(" ");

        // 一、缺勤不超过1次
        int absentCount = 0;
        for (String info : infos) {
            if (info.equals("absent")) {
                absentCount++;
                if (absentCount > 1) {
                    return false;
                }
            }
        }

        // 二、没有连续的迟到/早退
        List<String> cList = Arrays.asList("late", "leaveearly");
        for (int j = 1; j < infos.length; j++) {
            if (cList.contains(infos[j]) && cList.contains(infos[j - 1])) {
                return false;
            }
        }

        // 三、任意连续的7次考勤,缺勤/迟到/早退不超过3次
        int count = 0; // 违规次数
        int end = infos.length >= 7 ? 6 : infos.length;
        for (int k = 0; k < end; k++){
            if (cList.contains(infos[k])) {
                count++;
            }
        }
        if (count > 3) {
            return false;
        }
        //使用滑动窗口算法
        for (int start = 1; end < infos.length; start++, end++) {
            if (cList.contains(infos[end - 1])) {
                count++;
            }
            if (cList.contains(infos[start - 1])) {
                count--;
            }
            if (count > 3) {
                return false;
            }
        }
        return true;
    }