551. Student Attendance Record I

1. Description

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.

2. Example

Example 1:
Input: “PPALLP”
Output: True

Example 2:
Input: “PPALLL”
Output: False

3. Solutions

My Accepted Solution

n = i_record.size()
Time complexity: O(n)
Space complexity: O(n)

class Solution 
{
public:
    // bool checkRecord(string s)
    bool checkRecord(string &i_record) 
    {
        for(int i = 0, absentCount = 0; i < i_record.size(); i++)
        {
            if(i_record[i] == 'A') absentCount++;
            
            if(absentCount > 1 || i_record[i] == 'L' && i_record.substr(i, 3) == string("LLL")) 
                return false;
        }
        
        return true;
    }
};

3.1 Regular Expression

n = i_record.size()
Time complexity: O(n)
Space complexity: O(1)

class Solution 
{
public:
    // bool checkRecord(string s)
    bool checkRecord(string &i_record) 
    {
        string pattern(".*(A.*A|LLL).*");
        regex expression(pattern);
        
        return !regex_match(i_record, expression);
    }
};
Last updated:
Tags: String
comments powered by Disqus