这道题很难呀,其实用python一句话就很够了,float(s),但是这样就失去了题目本来的意义,对提高自己的能力并没有帮助。
于是这道题还是考虑出现的情况吧:
1.如果遇到±,必须出现在首位,或者eE的后面,并且不能超过s的长度。
2.如果遇到. ,后面必须要跟着数字,并且不能出现在最后一位。
3.如果遇到eE,后面不能出现. ,后面只能跟着数组和±。
4.如果不是数字,那就是错的。
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
#定义两个标志位,分别表示E或者e是否出现过,以及小数点.是否出现过。
#1. 以e(或E)为分隔,获得两个子字符串;e之前的字符串小数点只能出现一次;e之后的字符串不允许出现小数点;
#2. 符号位+或-只可能出现在两个子字符串的首位;
#3. e(或E)、小数点.不能出现在末尾
if not s:
return False
Sign_E=True
Sign_digit=True
for i in range(len(s)):
#有无+-
if s[i] in "+-" and (i==0 or s[i-1] in "eE") and i<len(s)-1:
continue
elif Sign_digit and s[i]==".":
Sign_digit=False
if i>=len(s)-1 or s[i+1] not in "1234567890":
return False
elif Sign_E and s[i] in "eE":
Sign_E=False
Sign_digit=False
if i>=len(s)-1 or s[i+1] not in "1234567890+-":
return False
elif s[i] not in "1234567890":
return False
return True