问题描述:
You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
‘A’: Absent.
‘L’: Late.
‘P’: Present.
The student is eligible for an attendance award if they meet both of the following criteria:
The student was absent (‘A’) for strictly fewer than 2 days total.
The student was never late (‘L’) for 3 or more consecutive days.
Return true if the student is eligible for an attendance award, or false otherwise.
判断该学生是否能拿出勤奖,如果该学生有少于两天旷课(A)记录,且没有连续三天及以上的迟到(L)记录。
思路:对于A,只计数就行。 对于L,如果前一次是L,这一次是L,下一次还是L,则返回false,否则就没事。**当然我们会注意到边界问题,就是说第一次没有上一次,最后一次没有下一次(用计算机语言说就是当i=0时,i-1报错;当i=s.length()-1时,i+1会报错)。这种情况的解决通法是补空格。**当然在第一位不用补空格因为加一句i>0就行,结尾补空格有利于简化条件语句。
代码如下:
class Solution {
public boolean checkRecord(String s) {
s=s+" ";
int A_counter=0;
for(int i=0; i<s.length()-1; i++){
if(s.charAt(i)=='A') A_counter++;
if (A_counter>=2) return false;
if((i>0)&&(s.charAt(i-1)=='L')&&(s.charAt(i)=='L')&&(s.charAt(i+1)=='L')) return false;
}
return true;
}
}
时间复杂度:O(n)