Description
Validate if a given string can be interpreted as a decimal number.
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
•Numbers 0-9
•Exponent - “e”
•Positive/negative sign - “+”/"-"
•Decimal point - “.”
Of course, the context of these characters also matters in the input.
Example
Some examples:
“0” => true
" 0.1 " => true
“abc” => false
“1 a” => false
“2e10” => true
" -90e3 " => true
" 1e" => false
“e3” => false
" 6e-1" => true
" 99e2.5 " => false
“53.5e93” => true
" --6 " => false
“-+3” => false
“95a54e53” => false
Submissions
解题思路首先想到的是将字符串转成浮点型判断即可。
实现代码如下:
class Solution:
def isNumber(self, s: str) -> bool:
try:
float(s)
return True
except:
return False
但觉得过于取巧,便从题目Note角度加以分析,有四种字符类型规则:
•Numbers 0-9:没有特殊规则。用Num标志。
•Exponent - “e”:需要在数字之后,且不能出现两个或以上。用Exp标志。
•Positive/negative sign - “+”/"-":不能连着两个或以上,不能在数字之后,在‘.’之后必须有e。用Sym 标志。
•Decimal point - “.”:不能在e之后,且不能出现两个或以上。用Dec 标志。
之后进行字符串遍历判断即可。
实现代码如下:
class Solution:
def isNumber(self, s: str) -> bool:
s = s.strip()
if not s:
return False
res = '0123456789e+-.'
Exp = Sym = Dec = Num = False
for i in s:
if i not in res:
return False
if i == 'e':
if (not Num) or Exp:
return False
Exp, Sym, Num = True, False, False
elif i =='.':
if Exp or Dec:
return False
Dec = True
elif i in'+-':
if Sym or Num or (Dec and not Exp):
return False
Sym = True
else:
Num = True
return Num