• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }

 

posted @ 2019-10-14 11:43  neverlandly  阅读(133)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3