1,题目要求
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).
也就是说,如果一个学生有超过一次的缺席(A)或者超过两次连续的迟到(L)就记为false。否则就记为true。
2,题目思路
一开始没有发现L是需要连续的,因此以为只需要进行简单的字母出现次数统计即可。
但是L必须是两次以上的连续出现时才会判断为false。因此可以直接进行字母的遍历并对出现次数进行记录即可。
3,程序源码:
#include<algorithm>
#include<iostream>
#include<vector>
#include<unordered_map>
#include <string>
using namespace std;
class Solution {
public:
bool checkRecord(string s) {
int numL=0, numA=0;
numA = count(s.begin(),s.end(),'A');//统计字符串中某一个字符出现的次数。
if(numA > 1)
return false;
for(int i=0;i<s.size();i++)
{
if(s[i]=='L')
numL++;
else
numL = 0;
if(numL>2)
return false;
}
return true;
}
};
int main()
{
Solution sol;
cout<<sol.checkRecord("LL");
return 0;
}
需要注意的是,一开始在LeetCode上运行代码时,numA和numL并没有进行初始化, 虽然在本地运行时时可以的,但是到LeetCode上缺出现结果错误,想来应该是初始化的方式有不同。再对其进行了初始化后,错误便消失了。