題目描述:
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
?
要完成的函數:
bool checkRecord(string s)
?
說明:
1、這道題給定一個字符串,其中只有三種字符P/L/A,分別代表在場/遲到/缺席。如果一個學生出現了一次以上的缺席,或者連續兩次以上的遲到,那么他就不能被獎勵。要求判斷是否某個學生能被獎勵。
2、關于A的,很容易,遍歷一遍字符串統計A出現次數,當次數大于1時,返回false,結束遍歷。
關于L的,也不難,遍歷一遍字符串,當碰到L時,判斷下一個字符和再下一個字符是否均為L,如果滿足,返回false,結束遍歷(這里要注意邊界條件,即下一個字符是否在字符串以內);如果不滿足,那么繼續處理下一個字符。
代碼如下:
bool checkRecord(string s) {int counta=0,countl=0;int s1=s.size();for(int i=0;i<s1;i++){if(s[i]=='A'){counta++;if(counta>1)return false;}else if(s[i+2]=='L'&&s[i+1]=='L'&&s[i]=='L'){if(i+2<s1)return false;}}return true;}
上述代碼實測6ms,beats 70.11% of cpp submissions。
?
3、另一種方法
參考了討論區的代碼實現,發現了另一種實際花費時間更少的方法。
代碼同樣分享給大家,如下:
bool checkRecord(string s) {int counta=0,countl=0;for(int i = 0;i < s.size();i++){if(s[i]=='A'){counta++;countl=0;//清空countl,重新開始if(counta>1)return false;}else if(s[i]=='L'){countl++;if(countl>2)return false;} else countl=0;}return true;}
上述代碼實測4ms,beats 100% of cpp submissions。
這樣寫代碼看起來更加“清爽”,判斷是否出現了連續的幾個相同字符,采用的是碰到其他字符就“清空”的方法。
而2中的方法,是碰到‘L’時繼續判斷下一個以及再下一個字符是否仍是'L'的方式,這種方法不需要引進countl的頻繁計算。
筆者還是更加喜歡“清爽”的代碼,當L出現幾百次才要return false的時候,明顯清爽代碼更省時間。
這道題目給予的啟示是:當要判斷字符是否連續出現時,可以采用“清空”的方法來做。