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 }
  • 相关阅读:
    委托与事件参数的简单运用
    C#消息队列专题
    项目计划流程简易描述
    cookies 客户端历史记录篇
    朋友做的VS2005插件:等号两边值互换
    SSE2指令集系列之二
    SSSE3指令集
    SSE3指令集系列
    SSE特殊指令集系列之一
    SSE2指令集系列之一
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/11670686.html
Copyright © 2011-2022 走看看