LeetCode 551. Student Attendance Record I(学生出勤记录 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
解法一
思路
这题只需要一个辅助变量contains_A
来记录当前是否已经出现A
,其初始值为False
。从前到后遍历字符串中每个字符,对每个字符:
如果是
A
:查看contains_A
的值:- 如果是
True
:返回False
。因为已经出现了A
。 - 如果是
False
:置contains_A
为True
。表示现在出现了A
。
- 如果是
- 如果是
L
:检查当前字符的前两个字符是否都是L
,若是则返回False
。表示出现了三个连续的L
。
Python
class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
contains_A = False
for i, letter in enumerate(s):
if (letter == 'A' and contains_A) or (letter == 'L' and i >= 2 and s[i - 1] == 'L' and s[i - 2] == 'L'):
return False
if letter == 'A' and not contains_A:
contains_A = True
return True
Java
public class Solution {
public boolean checkRecord(String s) {
boolean containsA = false;
for (int i = 0; i < s.length(); i++) {
char letter = s.charAt(i);
if ((letter == 'A' && containsA) || (letter == 'L' && i >= 2 && s.charAt(i - 1) == 'L' && s.charAt(i - 2) == 'L')) {
return false;
}
if (letter == 'A' && !containsA) {
containsA = true;
}
}
return true;
}
}
C++
class Solution {
public:
bool checkRecord(string s) {
bool containsA = false;
for (int i = 0; i < s.length(); i++) {
char letter = s[i];
if ((letter == 'A' && containsA) || (letter == 'L' && i >= 2 && s[i - 1] == 'L' && s[i - 2] == 'L')) {
return false;
}
if (letter == 'A' && !containsA) {
containsA = true;
}
}
return true;
}
};