题目:判断给定的字符串是否可以表示数值。
部分数值列举如下:
["+100", "5e2", "-123", "3.1416", "-1E-16", "0123"]
部分非数值列举如下:
["12e", "1a3.14", "1.2.3", "+-5", "12e+5.4"]
解题思路:创建状态机,根据当前的字否判断接下来可以接哪些字符。遍历字符串,如果出现的字符不在当前状态内,则输出False。
难点是状态机的建立,需要根据前序状态确定当前位置合法的字符。
class Solution:
def isNumber(self, s: str) -> bool:
state = [
{' ':0, 's':1, 'd':2, '.':8},
{'d':2, '.':8},
{'d':2, '.':3, 'e':4, ' ':7},
{'d':3, 'e':4, ' ':7},
{'s':5, 'd':6},
{'d':6},
{'d':6, ' ':7},
{' ':7},
{'d':3}
]
p = 0
for c in s:
if '0' <= c <= '9':
t = 'd'
elif c in '+-':
t = 's'
elif c in '. ':
t = c
elif c in 'eE':
t = 'e'
else:
return False
if t not in state[p]:
return False
p = state[p][t]
print(p)
return (p in [2,3,6,7])