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
解法一
计算A字符串出现的个数,和计算连续的L的个数。当A的个数超过1个,连续L的个数超过2个时,输出False。
public class Solution {
public boolean checkRecord(String s) {
if (s == null || s.length() == 0) {
return true;
}
int lengthA = 0;
int lengthL = 0;
char[] obj = s.toCharArray();
for (int i = 0; i < obj.length; i++) {
if (obj[i] == 'A') {
lengthA++;
lengthL = 0;
} else if (obj[i] == 'L') {
lengthL++;
} else {
lengthL = 0;
}
if (lengthA > 1 || lengthL > 2) {
return false;
}
}
return true;
}
}
解法二
正则表达式匹配
public class Solution {
public boolean checkRecord(String s) {
return !s.matches(".*LLL.*|.*A.*A.*");
}
}