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 student could be rewarded if their attendance record doesn’t contain:
You need to implement a function checkRecord(String s)
that returns true
if the student could be rewarded according to the given criteria, or false
otherwise.
Input: s = "PPALLP"
Output: true
Input: s = "PPALLL"
Output: false
Count ‘A’ characters: Traverse the string and count occurrences of ‘A’. If more than one ‘A’ is found, return false
.
Check for continuous ‘L’ characters: While traversing, check for sequences of three or more consecutive ‘L’ characters. If such a sequence is found, return false
.
Return true: If traversal completes without violating any rules, return true
.
public class Solution {
public boolean checkRecord(String s) {
int absents = 0;
int consecutiveLates = 0;
for (char c : s.toCharArray()) {
if (c == 'A') {
absents++;
if (absents > 1) {
return false; // More than one 'A'
}
}
if (c == 'L') {
consecutiveLates++;
if (consecutiveLates > 2) {
return false; // More than two continuous 'L'
}
} else {
consecutiveLates = 0; // Reset count if the current character is not 'L'
}
}
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
System.out.println(solution.checkRecord("PPALLP")); // should return true
System.out.println(solution.checkRecord("PPALLL")); // should return false
}
}
s
. We traverse the string once.By following these steps, we ensure the solution is both efficient and adheres to the problem’s constraints.
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?