标签:res record switch can col lse dex optimize style
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
标签:res record switch can col lse dex optimize style
原文地址:https://www.cnblogs.com/EdwardLiu/p/11670686.html