leetcode解题报告(29):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
分析
P不用管,A和L分别用两个变量aCount和lCount来记录。对于‘A’,每遇到一个就让aCount加一,大于等于2时直接退出主循环;对于‘L’,一旦遇到就进入一个循环,若下一个元素也为‘L’,则将lCount加1,直到不是‘L’或到了string的末尾为止。由于循环中多加了一次i,因此退出循环后要减一次i。如果此时lCount小于等于2,就置为0,否则退出主循环。
退出主循环后,判断lCount和aCount的个数,若符合条件则返回false,否则返回true。
代码如下:
class Solution {
public:
bool checkRecord(string s) {
int aCount = 0;
int lCount = 0;
for(int i = 0; i != s.size(); ++i){
if(aCount > 1)break;
if(s[i] == 'A')++aCount;
if(s[i] == 'L'){
while(s[i] == 'L' && i != s.size()){
++lCount;
++i;
}
--i;
if(lCount <= 2)lCount = 0;
else break;
}
}
if(aCount > 1 || lCount > 2)return false;
return true;
}
};