剑指offer刷题笔记53(python)
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
思路
在给出的可能出现的字符串中,有三个字符比较特殊,“±”,“e or E”,“.”,需要对着几种情况进行考虑:
“±”只能出现在字符串首或者字符“e or E”后面,且不能出现在最后一位。“.”不能出现在字符串首,也不能出现在字符串尾部,也不能出现在字符“e or E”后面,且不能出现两次。“e or E”不能出现两次且不能出现在字符串尾部。除了0–9和上面三个字符,不能出现其他的字符。 在具体的实现过程中,由于“e or E”和“.”不能出现两次,那么我们可以设置两个表示这两个字符能否在出现的标志。
代码
class Solution:
def isNumeric(self
, s
):
allowDot
= True
allowE
= 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 allowDot
and s
[i
] == ".":
allowDot
= False
if i
== 0 or i
== (len(s
) -1) or allowE
== False:
return False
elif allowE
and s
[i
] in "Ee":
allowE
= False
if i
== len(s
)-1:
return False
elif s
[i
] not in "0123456789":
return False
return True