Leetcode 551. Student Attendance Record I
You are given a string s
representing an attendance record for a student. The record only contains the following three characters:
A
: Absent.L
: Late.P
: Present.A student could be rewarded if their attendance record doesn’t contain:
A
(absent).L
(late).You need to implement a function bool checkRecord(string s)
that returns true
if the student’s attendance record is rewardable according to these criteria.
A
, L
, and P
.To solve this problem, we need to:
s
and count the occurrences of A
. If it exceeds 1, return false
.L
s. If found, return false
.true
.We will iterate through the string once, making this approach linear in time complexity.
Here’s the C++ implementation based on the outlined strategy:
#include <string>
using namespace std;
bool checkRecord(string s) {
int aCount = 0; // To count 'A's
int lStreak = 0; // To count consecutive 'L's
for (char c : s) {
if (c == 'A') {
aCount++;
if (aCount > 1) return false;
}
if (c == 'L') {
lStreak++;
if (lStreak > 2) return false;
} else {
lStreak = 0; // Reset streak if it's not 'L'
}
}
return true;
}
The time complexity of this approach is O(n), where n
is the length of the input string s
. We make a single pass through the string to count the occurrences of ‘A’ and check for streaks of ‘L’. The space complexity is O(1), as we are only using a few extra integer variables for counting.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?