问题:
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
解决:
① 直接遍历字符串。
public class Solution {//9ms
public boolean checkRecord(String s) {
int lc = 0;
int ac = 0;
for(char c : s.toCharArray()){
if(c == 'A') ac ++;
if(ac > 1) return false;
if(c == 'L') lc ++; //要连续的L多于2个。
else lc = 0;
if(lc > 2) return false;
}
return true;
}
}
② 另一种解法,判断至少三个连续的L,更简单一些。
public class Solution {//9ms
public boolean checkRecord(String s) {
int acount = 0;
for (int i = 0;i < s.length() ;i ++ ) {
if(s.charAt(i) == 'A'){
acount ++;
if (acount > 1) return false;
}
if (i <= s.length() - 3) {
if(s.charAt(i) == 'L' && s.charAt(i) == s.charAt(i + 1) && s.charAt(i) == s.charAt(i + 2)){
return false;
}
}
}
return true;
}
}