每日题解——2021-8-17

195 阅读1分钟

这是我参与8月更文挑战的第17天,活动详情查看:8月更文挑战

551. 学生出勤记录 I

给你一个字符串 s 表示一个学生的出勤记录,其中的每个字符用来标记当天的出勤情况(缺勤、迟到、到场)。记录中只含下面三种字符:

'A':Absent,缺勤 'L':Late,迟到 'P':Present,到场 如果学生能够 同时 满足下面两个条件,则可以获得出勤奖励:

按 总出勤 计,学生缺勤('A')严格 少于两天。 学生 不会 存在 连续 3 天或 3 天以上的迟到('L')记录。 如果学生可以获得出勤奖励,返回 true ;否则,返回 false 。

 

示例 1:

输入:s = "PPALLP"
输出:true
解释:学生缺勤次数少于 2 次,且不存在 3 天或以上的连续迟到记录。

示例 2:

输入:s = "PPALLL"
输出:false
解释:学生最后三天连续迟到,所以不满足出勤奖励的条件。

 

提示:

1 <= s.length <= 1000
s[i] 为 'A''L''P'

551. Student Attendance Record I

You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:

'A': Absent. 'L': Late. 'P': Present. The student is eligible for an attendance award if they meet both of the following criteria:

The student was absent ('A') for strictly fewer than 2 days total. The student was never late ('L') for 3 or more consecutive days. Return true if the student is eligible for an attendance award, or false otherwise.

 

Example 1:

Input: s = "PPALLP"
Output: true
Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.

Example 2:

Input: s = "PPALLL"
Output: false
Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.

 

Constraints:

1 <= s.length <= 1000
s[i] is either 'A', 'L', or 'P'.

解题思路

可奖励的出勤记录要求缺勤次数少于 22 和连续迟到次数少于 33。判断出勤记录是否可奖励,只需要遍历出勤记录,判断这两个条件是否同时满足即可。

遍历过程中,记录缺勤次数和连续迟到次数,根据遍历到的字符更新缺勤次数和连续迟到次数:

如果遇到 \text{`A'}‘A’,即缺勤,则将缺勤次数加 11,否则缺勤次数不变;

如果遇到 \text{`L'}‘L’,即迟到,则将连续迟到次数加 11,否则将连续迟到次数清零。

如果在更新缺勤次数和连续迟到次数之后,出现缺勤次数大于或等于 22 或者连续迟到次数大于或等于 33,则该出勤记录不满足可奖励的要求,返回 \text{false}false。如果遍历结束时未出现出勤记录不满足可奖励的要求的情况,则返回 \text{true}true

解题代码

var checkRecord = function(s) {
    let absents = 0, lates = 0;
    const n = s.length;
    for (let i = 0; i < n; i++) {
        const c = s[i];
        if (c === 'A') {
            absents++;
            if (absents >= 2) {
                return false;
            }
        }
        if (c === 'L') {
            lates++;
            if (lates >= 3) {
                return false;
            }
        } else {
            lates = 0;
        }
    }
    return true;
};