[leetcode] Student Attendance Record I

You are given a string representing an attendance record for a student. The record only contains the following three characters:
  1. 'A' : Absent.
  2. 'L' : Late.
  3. '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

分析:题目翻译一下:字符串s由'P'、‘A’、‘L’组成,要求s中如果A的个数大于1,或者连续超过3个L,就返回false,其余的返回true。这里连续的L要注意一下,也就是说一旦连续的L超过3个就是false,但是如果两个LL之后不是L,就没事。因此我们只要关注L和A就行了,先用一个二维数组保存一下个数。思路有了之后代码并不难写,代码如下:
 1 class Solution {
 2     public boolean checkRecord(String s) {
 3         int[] record = new int[2];
 4         int i = 0;
 5         while ( i < s.length() ){
 6             char c = s.charAt(i);
 7             if ( c == 'L' ) {
 8                 for ( int j = i ; j < s.length() ; j ++ ) 
 9                     if ( s.charAt(j) == 'L' ) record[1]++;
10                     else break;
11             }
12             if ( c == 'A' ) record[0]++;
13             if ( record[0] > 1 || record[1] > 2 ) return false;
14             record[1] = 0;
15             i++;
16         }
17         return true;
18     }
19 }

      其实第一个想法是用map,但是map比起数组来说时间复杂度还是太高了。因此使用数组减少时间。

      运行时间5ms,击败99.88%提交。

 
posted @ 2018-07-16 20:45  Lin.B  阅读(98)  评论(0编辑  收藏  举报