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

    1-liner

    s.contains("") normally is O(nm), but can be optimized to be O(n)

    1 public class Solution {
    2     public boolean checkRecord(String s) {
    3         if(s.indexOf("A") != s.lastIndexOf("A") || s.contains("LLL"))
    4             return false;
    5         return true;
    6     }
    7 }

    O(n) scan

     1 class Solution {
     2     public boolean checkRecord(String s) {
     3         int countA = 0, countB = 0;
     4         for (char c : s.toCharArray()) {
     5             switch (c) {
     6                 case 'A': 
     7                     if (countA == 1) return false;
     8                     countA ++;
     9                     countB = 0;
    10                     break;
    11                 case 'L':
    12                     if (countB == 2) return false;
    13                     countB ++;
    14                     break;
    15                 default:
    16                     countB = 0;
    17             }
    18         }
    19         return true;
    20     }
    21 }
  • 相关阅读:
    poj 3243 Clever Y(BabyStep GiantStep)
    poj 2417 Discrete Logging
    poj 3481 Double Queue
    hdu 4046 Panda
    hdu 2896 病毒侵袭
    poj 1442 Black Box
    hdu 2815 Mod Tree
    hdu 3065 病毒侵袭持续中
    hdu 1576 A/B
    所有控件
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/11670686.html
Copyright © 2011-2022 走看看