zoukankan      html  css  js  c++  java
  • [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%提交。

     
  • 相关阅读:
    Algorithm --> KMP算法
    Algorithm --> 快速排序
    Algorithm --> 阶乘和因子
    Algorithm --> Dijkstra和Floyd最短路径算法
    Algorithm --> 二分图最大匹配
    Algorithm --> 邮票连续组合问题
    Algorithm --> 字母重排
    Algorithm --> 6174问题
    Algorithm --> 字符串中最长不重合子串长度
    Algorithm --> DFS和BFS
  • 原文地址:https://www.cnblogs.com/boris1221/p/9320020.html
Copyright © 2011-2022 走看看