Leetcode: Student Attendance Record I
Posted neverlandly
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于Leetcode: Student Attendance Record I的主要内容,如果未能解决你的问题,请参考以下文章
551. Student Attendance Record I(LeetCode)
leetcode_easy551. Student Attendance Record I
LeetCode 551. Student Attendance Record I (学生出勤纪录 I)
Leetcode-552 Student Attendance Record II(学生出勤记录 II)