551-学生出勤记录 I

551-学生出勤记录 I

给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:

  1. 'A' : Absent,缺勤
  2. 'L' : Late,迟到
  3. 'P' : Present,到场

如果一个学生的出勤记录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。

你需要根据这个学生的出勤记录判断他是否会被奖赏。

示例 1:

输入: "PPALLP"
输出: True

示例 2:

输入: "PPALLL"
输出: False

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/student-attendance-record-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    public boolean checkRecord(String s) {
        // A>=2 || contains(LLL) → false
        char[] chars = s.toCharArray();
        int numOfA = 0;
        for(int i = 0; i < chars.length; i++) {
            if(chars[i] == 'A') {
                numOfA++;
                if(numOfA == 2) {
                    return false;
                }
            } else if(chars[i] == 'L') {
                if(i + 2 < chars.length && chars[i + 1] == 'L' && chars[i + 2] == 'L') {
                    return false;
                }
            }
        }
        return true;
    }

改进:优化空间使用

    public boolean checkRecord(String s) {
        // A>=2 || contains(LLL) → false
        int numOfA = 0;
        int numofContiL = 0;
        for (char c : s.toCharArray()) {
            if (c == 'L') {
                numofContiL++;
                if (numofContiL == 3) {
                    return false;
                }
            } else {
                numofContiL = 0;
                if (c == 'A') {
                    numOfA++;
                    if (numOfA == 2) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

官方题解:https://leetcode-cn.com/problems/student-attendance-record-i/solution/xue-sheng-chu-qin-ji-lu-i-by-leetcode/

猜你喜欢

转载自www.cnblogs.com/angelica-duhurica/p/12237805.html