0%

student-attendance-record-i

Student Attendance Record I – LeetCode 551

Problem

Description

You are given a string representing an attendance record for a student. The record only contains the following three characters:

  1. ‘A’ : Absent.
  2. ‘L’ : Late.
  3. ‘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.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool checkRecord(string s) {
int cntA = 0, cntL = 0;
for (char c : s) {
if (c == 'A') {
if (++cntA > 1) return false;
cntL = 0;
} else if (c == 'L') {
if (++cntL > 2) return false;
} else {
cntL = 0;
}
}
return true;
}
};

思路

简单的匹配。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$0$ ms,排名$0\%$

Better

思路

发一个用正则表达式的解法,因为需要在运行时编译正则表达式,所以会慢一点,此处为了开开眼界。
耗时$4$ ms,排名$83.48\%$

Code

1
2
3
4
5
6
class Solution {
public:
bool checkRecord(string s) {
return !regex_search(s, regex("A.*A|LLL"));
}
};