StudentAttendanceRecordI2 [source code]

public class StudentAttendanceRecordI2 {
    public boolean checkRecord(String s) {
        char[] chars = s.toCharArray();
        int countA = 0, countL = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == 'L') {
                if (++countL > 2) return false;
            } else {
                countL = 0;
                if (chars[i] == 'A' && ++countA > 1) return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        StudentAttendanceRecordI2 tester = new StudentAttendanceRecordI2();
        String i1 = "PPALLPLLPLL";
        System.out.println(tester.checkRecord(i1));
    }
}

这里就是实现了ver1的笔记里面提到的一个用一个单独的 counter 来记录 run 的长度的思路, 整体实现还是比较简单的.

刚开始循环写成了这样:

for (int i = 0; i < chars.length; i++) {  
    if (chars[i] == 'L' && ++countL > 2) return false;  
    else {  
        countL = 0;  
        if (chars[i] == 'A' && ++countA > 1) return false;  
    }  
}

这个的错误就在于你把"碰到 L" 和"L 触发"学到了一个 land 里面, 那么你下面的 else 的意思就不一样了. 你这个 else 里面就包含了"碰到 L 但是 L 没有触发 false" 的情况, 这个不是你想要的.
有时候想要把代码写的简洁一些是好的想法, 不过很容易就把逻辑改错了.

最后速度居然变慢了: 9(69). 可能是因为现在我每个 iteration 都要多一个 counter access, 而之前虽然有 array access, 但是只在少数的几个 i 才会触发.


Problem Description

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
Difficulty:Easy
Category:Algorithms
Acceptance:43.57%
Contributor: fallcreek
Companies
google
Related Topics
string
Similar Questions
Student Attendance Record II

results matching ""

    No results matching ""