LeetCode 551: Student Attendance Record I

String

Problem Description

Explanation:

To solve this problem, we need to iterate through the given attendance record and keep track of the number of absences and consecutive late days. We will maintain two variables to count the absences and late days. If we encounter an absence ('A'), we will increment the absence count. If we encounter a late day ('L'), we will increment the late day count and check if it has reached 3 consecutive days. If the late day count reaches 3, we return false. If the absence count is strictly less than 2 and there are no 3 consecutive late days, we return true.

  • Initialize absence count and late day count to 0.
  • Iterate through the attendance record.
  • For each character:
    • If 'A' encountered, increment absence count.
    • If 'L' encountered, increment late day count and check for 3 consecutive late days.
    • If 'P' encountered, reset late day count to 0.
  • Return true if absence count < 2 and no 3 consecutive late days, else return false.

Time Complexity: O(n), where n is the length of the input string s. Space Complexity: O(1)

:

Solutions

class Solution {
    public boolean checkRecord(String s) {
        int absences = 0;
        int lateDays = 0;

        for (char c : s.toCharArray()) {
            if (c == 'A') {
                absences++;
                if (absences >= 2) {
                    return false;
                }
            } else if (c == 'L') {
                lateDays++;
                if (lateDays >= 3) {
                    return false;
                }
            } else {
                lateDays = 0;
            }
        }

        return true;
    }
}

Loading editor...