Monday, February 18, 2019

Leetcode 551. Student Attendance Record I

You are given a string representing an attendance record for a student. The record only contains the following three characters:
  1. 'A' : Absent.
  2. 'L' : Late.
  3. 'P' : Present.
A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).
You need to return whether the student could be rewarded according to his attendance record.
Example 1:
Input: "PPALLP"
Output: True
Example 2:
Input: "PPALLL"
Output: False

Code (Java):
class Solution {
    public boolean checkRecord(String s) {
        if (s == null || s.length() < 2) {
            return true;
        }

        int cLate = 0;
        int cAbsent = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == 'A') {
                cAbsent++;
            } else if (c == 'L') {
                cLate = 0;
                // check the number of contiguous lates
                //
                while (i < s.length() && s.charAt(i) == 'L') {
                    cLate++;
                    i++;
                }
                i--;
            }

            if (cAbsent > 1 || cLate > 2) {
                return false;
            }
        }

        return true;
    }
}

No comments:

Post a Comment