1. 程式人生 > >LeetCode-Student Attendance Record I

LeetCode-Student Attendance Record I

Description: 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

Example 2:

Input: "PPALLL"
Output: False

題意:給定一個字串記錄學生的考勤情況;有下面的三種情況

  • ‘A’ : 缺席
  • ‘L’ : 遲到
  • ‘P’ : 到場

有下列情況的有獎勵:A的次數不超過1次或者L連續出現的次數不超過2次;

解法:對於A的出現次數我們直接統計就可以了,現在需要考慮的是連續出現的L的次數,每當L中止連續出現的時候,應當重新計數;

class Solution {
    public boolean checkRecord(String s) {
        int cntA = 0;
        int cntL = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'A') {
                cntA++;
            } else if (s.charAt(i) == 'L') {
                if (cntL > 0 && s.charAt(i - 1
) == 'L') { cntL++; } else { cntL = 1; } } if (cntL > 2 || cntA > 1) { return false; } } return true; } }