题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
思路
- 需要三个变量,来看之前是否已经有了e|E,点,符号
- e|E之前不能再有e|E,e|E不能在最后
- 点之前不能再有点,同时点之前也不能有e|E
- 如果之前有符号了,那么只能出现在e|E之后
- 如果之前没有,可以出现在第一位或者e|E之后
- 判断数字是否为0~9
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if not s:
return False
hasE = False
hasDot = False
hasFlag = False
for i in range(len(s)):
if s[i] == "e" or s[i] == "E":
if hasE or i == len(s) - 1:
return False
hasE = True
elif s[i] == ".":
if hasDot or hasE:
return False
hasDot = True
elif s[i] == "+" or s[i] == "-":
if hasFlag:
if s[i - 1] != "e" and s[i - 1] != "E":
return False
else:
if i != 0 and (s[i - 1] != "e" and s[i - 1] != "E"):
return False
hasFlag = True
else:
if s[i] < "0" or s[i] > "9":
return False
return True
测试用例
if __name__=='__main__':
s=Solution()
ss="+123.45e+6"
print(s.isNumeric(ss))