LeetCode-Student_Attendance_Record_I

題目:

You are given a string representing an attendance record for a student. The record only contains the following three characters:

  1. 'A' : Absent.
  2. 'L' : Late.
  3. '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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章