请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、"5e2"、"-123"、"3.1416"、"0123"都表示数值,但"12e"、"1a3.14"、"1.2.3"、"+-5"、"-1E-16"及"12e+5.4"都不是。
判断字符串,那岂不是用try+float(s)就行了。尝试后果然可以,代码如下:
class Solution:
def isNumber(self, s: str) -> bool:
try:
float(s)
return True
except:
return False
结果很好,再次证明python内置函数很好:
下面是正常的求解方法:有限状态自动机(FSM "finite state machine" 或者FSA "finite state automaton" )
有限状态自动机
思路
首先确定不同的状态和转移条件;
确定能够成功返回的状态;
画出状态转移表;
判断输入字符串能否达到最终的成功返回状态。
代码如下
首先给出了状态转移表和转移条件,再判断最终返回状态是否为合法状态即可。
class Solution:
def isNumber(self, s: str) -> bool:
if not s:return False
transTable = [
[1,2,7,-1,-1,0],
[-1,2,7,-1,-1,-1],
[-1,2,3,4,-1,9],
[-1,3,-1,4,-1,9],
[6,5,-1,-1,-1,-1],
[-1,5,-1,-1,-1,9],
[-1,5,-1,-1,-1,-1],
[-1,8,-1,-1,-1,-1],
[-1,8,-1,4,-1,9],
[-1,-1,-1,-1,-1,9]
]
cols = {
"sign":0,
"number":1,
".":2,
"exp":3,
"other":4,
"blank":5
}
def get_col(c):
if c.isdigit():return 'number'
elif c in {'+','-'}:return 'sign'
elif c == '.':return '.'
elif c in {'E','e'}:return 'exp'
elif c == ' ':return 'blank'
else:return 'other'
legal_state = {2,3,5,8,9}
state = 0
for c in s:
state = transTable[state][cols[get_col(c)]]
if state == -1:return False
return True if state in legal_state else False
参考代码: