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:
'A' : Absent.
'L' : Late.
'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

Solution:

思路:
分别记录 缺勤 和 连续迟到 的次数,
如果当前遇到缺勤,那么缺勤计数器自增1,如果此时次数大于1了,说明已经不是优秀了,直接返回false,否则连续迟到计数器清零。如果当前遇到迟到,那么连续迟到计数器自增1,如果此时连续迟到计数器大于1了,说明已经不是优秀了,直接返回false。如果遇到正常出勤了,那么连续迟到计数器清零.
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public boolean checkRecord(String s) {
        int countA=0; // Absent
        int continuosL = 0; // Late
        
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == 'A'){
                countA++;
                continuosL = 0;
            }
            else if(s.charAt(i) == 'L'){
                continuosL++;
            }
            else{
                continuosL = 0;
            }
            if(countA > 1 || continuosL > 2 ){
                return false;
            }
        }
        return true;

    }
}

你可能感兴趣的:(551. Student Attendance Record I)