Come from : [https://leetcode-cn.com/problems/student-attendance-record-i/]
551. Student Attendance Record I
1.Question
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
2.Answer
easy 类型题目。
我的暴力解题思路:
- 统计 ‘A’ 和 ‘L’ 出现的次数,分别用 a 和 b 表示。
- 若 a <= 1 && b <=2 返回true。
- 若 a <= 1 && b > 2 ,则继续 判断 有没有 三个连续的 ‘L’,如果有三个连续的,则返回 false,没有三个连续的则返回 true。
- 若 a > 1 ,返回 false。
AC代码如下:(比较low。。。)
class Solution {
public:
bool checkRecord(string s) {
int a = 0;
int b = 0;
bool ok = true;
for(auto c : s)
{
if(c == 'A')
{
++a;
}
if(c == 'L')
{
++b;
}
}
if(a <= 1 && b <= 2)
{
ok = true;
}
else if(a <= 1 && b > 2)
{
for(int i = 0; i < s.size() - 2; ++i)
{
if(s[i] == 'L')
{
if(s[i+1] == 'L')
{
if(s[i+2] == 'L')
{
ok = false;
}
}
}
}
}
else
{
ok = false;
}
return ok;
}
};
3.大神们的解决方案
排名第一的 解法。。。比我的简洁啊 啊 啊。。。
AC代码如下:
class Solution {
public:
bool checkRecord(string s) {
int countA = 0, countL = 0;
for(size_t i = 0; i < s.size(); ++i)
{
if(s[i] == 'L')
{
countL++;
if(countL > 2)
return false;
continue;
}
countL = 0;
if(s[i] == 'A')
{
countA++;
if(countA > 1)
return false;
}
}
return true;
}
};
4.我的收获
Fighting~~~
2019/5/19 胡云层 于南京 82