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
REF. Oleksandr Pyrohov's One line Java solution without Regex
I'm using two simple checks:
- String doesn't contains
LLL
.- The first occurrence of
A
is equals to the last occurrence ofA
.
public class Solution {
public boolean checkRecord(String s) {
return !s.contains("LLL") && (s.indexOf("A") == s.lastIndexOf("A"));
}
}
Since the pattern is determined, an alternative is regular expression like compton_scatter's solution,
public boolean checkRecord(String s) {
return !s.matches(".*LLL.*|.*A.*A.*");
}
The first one's runtime takes 11 ms and beats 34.72% of submission, and later takes 19 ms and beats 6.45% of submissions.