请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、"5e2"、"-123"、"3.1416"、"-1E-16"、"0123"都表示数值,但"12e"、"1a3.14"、"1.2.3"、"+-5"及"12e+5.4"都不是。
PYthon 解答:
1.自动机状态转移
class Solution:
def isNumber(self, s: str) -> bool:
states = [
{' ':0, 's':1, 'd':2, '.':4},
{'d':2, '.':4, },
{'d':2, '.':3, 'e':5, ' ':8},
{'d':3, 'e':5, ' ':8},
{'d':3},
{'s':6, 'd':7},
{'d':7},
{'d':7, ' ':8},
{' ':8}
]
state = 0
t = None
for c in s:
if '0' <= c <= '9':
t = 'd'
elif c in '+-':
t = 's'
elif c in 'eE':
t = 'e'
elif c in '. ':
t = c
else:
t = c
if t in states[state].keys():
state = states[state][t]
else: return False
if state in [2, 3, 7, 8]:
return True
else: return False
留言