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.
Example 1:
Input: "PPALLP"
Output: true
Approach
Java
public class StudentAttendanceRecordI {public static void main(String[] args) {String str = "PPALLP";System.out.println(checkRecord(str));}static boolean checkRecord(String s) {int cnt = 0, n = s.length();for (int i = 0; i < n; i++)if (s.charAt(i) == 'A')cnt++;if (cnt > 1)return false;int i = 0;while (i < n && s.charAt(i) != 'L')i++;while (i < n) {if (s.charAt(i) == 'L') {cnt = 0;while (i < n && s.charAt(i) == 'L') {cnt++;i++;}i++;if (cnt > 2)return false;} elsei++;}return true;}}
C++
#include <bits/stdc++.h>using namespace std;bool checkRecord(string s){int cnt = 0, n = s.size();for (int i = 0; i < n; i++)if (s[i] == 'A')cnt++;if (cnt > 1)return false;int i = 0;while (i < n && s[i] != 'L')i++;while (i < n){if (s[i] == 'L'){int cnt = 0;while (i < n && s[i] == 'L'){cnt++;i++;}i++;if (cnt > 2)return false;}elsei++;}return true;}int main(){string str = "PPALLP";if (checkRecord(str))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment