Student Attendance Record I
Problem
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
Regex Solution O(n) time
public class Solution {
public boolean checkRecord(String s) {
return !s.matches(".*(A.*A|LLL).*"); //"." represents any character
}
}
Regular Solution without Regex O(n) time
public class Solution {
public boolean checkRecord(String s) {
if (s.indexOf("A") != s.lastIndexOf("A") || s.contains("LLL")) return false;
return true;
}
}
Analysis
A typical String pattern problem
As long as you face pattern in string, the first you should remember is to use Regex
Notice that "|"
means or
in regex not "||"
The second solution make use of indexOf()
and lastIndexOf()
methods to check frequencies of "A"
Both solutions have single pass, hence their time complexity is O(n)