版权声明:made by YYT https://blog.csdn.net/qq_37621506/article/details/83794805
1.题目
给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个字符:
‘A’ : Absent,缺勤
‘L’ : Late,迟到
‘P’ : Present,到场
如果一个学生的出勤纪录中不超过一个’A’(缺勤)并且不超过两个连续的’L’(迟到),那么这个学生会被奖赏。
你需要根据这个学生的出勤纪录判断他是否会被奖赏。
2.思路
遍历字符串,计算A的个数,大于1则返回false;
当遇到L的时候,判断其后两位是否均为L,是则返回false;
3.代码
bool Solution::checkRecord(string s)
{
int len=s.length();
int absent=0;
for(int i=0;i<len;i++){
if(s[i]=='A'){
absent++;
if(absent>=2)
return false;
}
if(s[i]=='L'){
if(i>=len-2)
return true;
else if(s[i+1]=='L'&&s[i+2]=='L')
return false;
}
return true;
}
}
4.优秀案例
class Solution {
public:
bool checkRecord(string s) {
int num_A = 0, num_L = 0, count = 0;
s += ' ';
for(int i=0; i<s.length(); i++){
if(s[i] == 'A') num_A++;
if(s[i] == 'L'){
count++;
}else{
num_L = max(num_L, count);
count = 0;
}
}
return num_A <=1 && num_L <=2;
}
}