题目描述

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_ATrue。表示现在出现了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;
    }
};