算法笔记: 力扣#551 学生出勤记录 i

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class :
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
has_absent=False
for i, c in enumerate(s):
if c == 'A':
if has_absent:
return False
has_absent=True
if i>1 and c=='L' and s[i-1]=='L' and s[i-2]=='L':
return False
return True

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class {
public boolean checkRecord(String s) {
boolean hasAbsent = false;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i)=='A'){
if(hasAbsent){ return false; }
hasAbsent = true;
}
if(i>1 && s.charAt(i)=='L' && s.charAt(i-1)=='L' && s.charAt(i-2)=='L'){
return false;
}
}
return true;
}
}

时间复杂度

O(n).

空间复杂度

O(1).

链接


551. Student Attendance Record I
551. 学生出勤记录 I
(English version) Algorithm Notes: Leetcode#551 Student Attendance Record I