GuoXin Li's Blog

LeetCode551. Student Attendance Record I

字数统计: 311阅读时长: 1 min
2020/02/27 Share

551. Student Attendance Record I

551. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//java
class Solution {
public boolean checkRecord(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++){
if(count > 1){
return false;
}
if(s.charAt(i) == 'A'){
count++;
}
if( i < (s.length()-2) && (s.charAt(i) == 'L') && (s.charAt(i+1) == 'L') && (s.charAt(i+2) == 'L')){
return false;
}
}
return (count < 2) ;
//return (count < 2) && (s.indexOf("LLL") < 0)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//c++
//from Huahua, good solution
class Solution {
public:
bool checkRecord(string s) {
int a{0};
int l{0};
for (char c : s){
if(c == 'A') ++a;
if(c == 'L') ++l;
else l = 0;
if(a > 1 || l > 2 ) return false;
}
return true;
}
};
1
2
3
4
5
6
7
//c++
class Solution {
public:
bool checkRecord(string s) {
return s.find('A', s.find('A') + 1) == -1 && s.find("LLL") == -1;
}
};

Time Complexity: solution1: O(n) + O(n), solution2: O(n)

Space Complexity: O(1)

note:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(){

string s = "lipsky";

string p = "l";

int ans = s.find(p, 2) ;  //find "l" from 2 index in s; if true return index, else return -1 (same as java)

cout<<ans<<endl;

system("pause");

}
CATALOG
  1. 1. 551. Student Attendance Record I
  2. 2. Example 1: