题目地址:
https://www.lintcode.com/problem/student-attendance-record-i/description
给定一个出勤记录,以字符串表示,如果有超过一个A
或者连续超过两个L
,则返回false,否则返回true。
直接遍历字符串再判断。代码如下:
public class Solution {
/**
* @param s: a string
* @return: whether the student could be rewarded according to his attendance record
*/
public boolean checkRecord(String s) {
// Write your code here
int countA = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'A') {
countA++;
}
if (s.charAt(i) == 'L') {
int countL = 0, j = i;
while (j < s.length() && s.charAt(j) == 'L') {
countL++;
j++;
}
if (countL > 2) {
return false;
}
i = j - 1;
}
}
return countA <= 1;
}
}
时间复杂度 O ( l s ) O(l_s) O(ls),空间 O ( 1 ) O(1) O(1)。