Leetcode 551: Student Attendance Record I

问题描述:
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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值