Description

You are given a string representing an attendance record for a student. The record only contains the following three characters:

  1. ‘A’ : Absent.
  2. ‘L’ : Late.
  3. ‘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

Example 1

1
2
Input: "PPALLP"
Output: True

Example 2

1
2
Input: "PPALLL"
Output: False

Interface

1
2
3
4
5
6
class Solution {
public:
bool checkRecord(string s) {

}
};

Solution

先分析题目,根据题目的意思是说,只要缺勤超过两次或者迟到超过两次且是连续的就应该返回 false,缺勤超过两次这个直接记录就 OK,而这题的重点用更通俗的话来讲就是连续两天以上迟到,其实最简单的做法就是用一个变量 late 记录迟到的次数,迟到则加 1,不是迟到的则将 late 重置为 0,然后判断 late 是否大于 2 即可。这题算是比较简单的,巧妙的 if-else 就可以做出。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool checkRecord(string s) {
int abs = 0, late = 0;
for (int i = 0; i < s.length(); ++i) {
if (s[i] == 'A') abs++;
if (s[i] == 'L') late++;
else late = 0;
if (abs > 1 || late > 2) return false;
}
return true;
}
};