LeetCode 题解工作台

学生出勤记录 I

给你一个字符串 s 表示一个学生的出勤记录,其中的每个字符用来标记当天的出勤情况(缺勤、迟到、到场)。记录中只含下面三种字符: 'A' :Absent,缺勤 'L' :Late,迟到 'P' :Present,到场 如果学生能够 同时 满足下面两个条件,则可以获得出勤奖励: 按 总出勤 计,学生缺勤…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们可以遍历字符串 ,记录字符 `'A'` 和字符串 `"LLL"` 的出现次数。如果字符 `'A'` 的出现次数小于 ,且字符串 `"LLL"` 没有出现过,则可以将该字符串视作记录合法,返回 `true`,否则返回 `false`。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s 表示一个学生的出勤记录,其中的每个字符用来标记当天的出勤情况(缺勤、迟到、到场)。记录中只含下面三种字符:

  • 'A':Absent,缺勤
  • 'L':Late,迟到
  • 'P':Present,到场

如果学生能够 同时 满足下面两个条件,则可以获得出勤奖励:

  • 总出勤 计,学生缺勤('A'严格 少于两天。
  • 学生 不会 存在 连续 3 天或 连续 3 天以上的迟到('L')记录。

如果学生可以获得出勤奖励,返回 true ;否则,返回 false

 

示例 1:

输入:s = "PPALLP"
输出:true
解释:学生缺勤次数少于 2 次,且不存在 3 天或以上的连续迟到记录。

示例 2:

输入:s = "PPALLL"
输出:false
解释:学生最后三天连续迟到,所以不满足出勤奖励的条件。

 

提示:

  • 1 <= s.length <= 1000
  • s[i]'A''L''P'
lightbulb

解题思路

方法一:字符串遍历

我们可以遍历字符串 ss,记录字符 'A' 和字符串 "LLL" 的出现次数。如果字符 'A' 的出现次数小于 22,且字符串 "LLL" 没有出现过,则可以将该字符串视作记录合法,返回 true,否则返回 false

时间复杂度 O(n)O(n),其中 nn 是字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def checkRecord(self, s: str) -> bool:
        return s.count('A') < 2 and 'LLL' not in s
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate correctly identifies the need for a linear scan of the string.

  • question_mark

    Candidate efficiently handles the dual check for both 'A' count and 'L' streaks in one pass.

  • question_mark

    Candidate demonstrates awareness of optimal time complexity for this problem.

warning

常见陷阱

外企场景
  • error

    Failing to handle edge cases where the string contains less than three characters.

  • error

    Not returning early if the number of absences exceeds 1 or three consecutive 'L's are detected.

  • error

    Overcomplicating the solution with unnecessary operations, leading to higher time or space complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check for exactly one absence or at least two consecutive late days.

  • arrow_right_alt

    Determine eligibility based on a maximum of two absences and no 'L' streaks longer than two days.

  • arrow_right_alt

    Extend the logic to check for a specific number of tardies (e.g., exactly one day late allowed).

help

常见问题

外企场景

学生出勤记录 I题解:String-driven solution … | LeetCode #551 简单