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
題目看起來(lái)很簡(jiǎn)單,統(tǒng)計(jì)A和L的次數(shù),超出所規(guī)定的就false
def checkRecord(s):
"""
:type s: str
:rtype: bool
"""
num_A = 0
num_L = 0
for i in list(s):
if i == 'A':
num_A = num_A + 1
elif i == 'L':
num_L = num_L + 1
else:
pass
return num_A <= 1 and num_L <= 2
提交的時(shí)候報(bào)錯(cuò),用例是LPPALL
仔細(xì)讀題發(fā)現(xiàn) continue 是需要L是連續(xù)的葛超,想到用正則
import re
re.match('正則表達(dá)式'革骨,s)
寫(xiě)正則的時(shí)候邊查邊寫(xiě)谆棱,沒(méi)成功·····
想了其他做法:
class Solution(object):
def checkRecord(self,s):
"""
:type s: str
:rtype: bool
"""
num_A = 0
num_L = 0
for i in list(s):
if i == 'A':
num_A = num_A + 1
num_L = 0
elif i == 'L':
num_L = num_L + 1
else:
num_L = 0
if num_A > 1 or num_L > 2:
return False
return True
這個(gè)本來(lái)想的是設(shè)置一個(gè)tag值用來(lái)判斷前面的是不是L赋朦,忘了是因?yàn)槭裁礇](méi)成功,下次再寫(xiě)一下龄广。
另一種簡(jiǎn)單做法:
def checkRecord(s):
"""
:type s: str
:rtype: bool
"""
num_A = 0
num_L = 0
for i in list(s):
if i == 'A':
num_A = num_A + 1
elif i == 'L':
num_L = num_L + 1
else:
pass
return num_A <= 1 and 'LLL' not in s
第一種python做法改成 c
#include <stdio.h>
#include <string.h>
int checkRecord(char* s) {
int numA = 0;
int numL = 0;
int len = strlen(s);
for (int i = 0;i <= len;i++){
if(s[i] == 'A'){
numA++;
numL = 0;
}else if(s[i] == 'L'){
numL++;
}else{
numL = 0;
}
if(numA >= 2 || numL >= 3){
return 0;
}
}
return 1;
}
發(fā)現(xiàn):
c 的 && 邏輯運(yùn)算符:前面那個(gè)如果成立的話惰赋,不會(huì)判斷后面那個(gè)
但是python 不會(huì)宰掉,兩個(gè)都會(huì)判斷
eval() 函數(shù)可以把字符串變成算式進(jìn)行運(yùn)算
eval('2+3')