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
题目看起来很简单,统计A和L的次数,超出所规定的就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
提交的时候报错,用例是LPPALL
仔细读题发现 continue 是需要L是连续的,想到用正则
import re
re.match('正则表达式',s)
写正则的时候边查边写,没成功·····
想了其他做法:
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
这个本来想的是设置一个tag值用来判断前面的是不是L,忘了是因为什么没成功,下次再写一下。
另一种简单做法:
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;
}
发现:
c 的 && 逻辑运算符:前面那个如果成立的话,不会判断后面那个
但是python 不会,两个都会判断
eval() 函数可以把字符串变成算式进行运算
eval('2+3')
网友评论