In this post, we will learn to solve a problem from LeetCode mock questions. The task is to determine attendance reward for a student should be rewarded based on his attendance records.
The solution here is written in C# language.
Problem Description From LeetCode
You are given a string 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 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.
Solution Approach Algorithm To Determine Attendance Reward
We can come up with a solution algorithm with the following approach.
- Loop over each characters of the attendance string representation.
- Maintain a counter for absent identifier.
- Keep a reference of the last two characters of ongoing loop.
- Break the loop if any of the conditions meet for absent or late cases.
- Return result as true or false value.
Solution In C# To Determine Attendance Reward
Here, we have the actual solution implementation in C# language.
public bool CheckRecord(string s) {
var aCounter = 0;
var lastTwoChars = "ZZ";
var result = true;
foreach (char c in s)
{
if(c == 'L') {
if(lastTwoChars == "LL") {
result = false;
break;
}
}
else if(c == 'A') {
aCounter ++;
if(aCounter > 1) {
result = false;
break;
}
}
lastTwoChars = lastTwoChars.Substring(1) + c.ToString();
}
return result;
}
Finishing Up
This was a relatively an easy problem. There can be more than one solution to the problem so feel free to modify this one or come up with your own solution too!
Checkout more problems from LeetCode.
Checkout our other article on .NET Core and C#.