题目:
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.‘A’:缺勤。
2.‘L’:迟到。
3.‘P’:出勤。
一个学生将被奖励如果他的出勤记录中不包含超过一个‘A’(缺勤)或者超过两个连续的‘L’(迟到)。
你需要返回这个学生能否被奖励根据他的出勤记录。
例子 1:
输入:“PPALLP”
输出:True
例子 2:
输入:“PPALLL”
输出:False
思路:(参考:http://www.cnblogs.com/grandyang/p/6736484.html)
利用string中的find函数,当同时满足下面两个条件就是优秀,第一个条件是找不到A,或者正着找A和逆着找A在同一个位置(说明只有一个A);第二个条件是找不到LLL,说明不能连续迟到三次。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool checkRecord(string s) {
return (s.find("A") == s.npos|| s.find("A") == s.rfind("A")) && s.find("LLL") == s.npos; //s.npos表示查找失败,string::npos对应-1
}
};
int main()
{
Solution s;
string str = "PPALLP";
bool result = s.checkRecord(str);
cout << result << endl;
return 0;
}