class Solution:
def isNumber(self, s: str) -> bool:
last_dot = last_e = last_d = -1
for i, c in enumerate(s):
if c.isdigit():
last_d = i
elif c == '.':
if last_dot != -1 or last_e != -1: return False
last_dot = i
elif c.lower() == 'e':
if last_d == -1 or last_e != -1: return False
last_e = i
elif c == '+' or c == '-':
if i == 0 or s[i-1].lower() == 'e':
continue
else:
return False
else:
return False
return s[-1].isdigit() or (s[-1] == '.' and last_d != -1)
class Solution:
def isNumber(self, s: str) -> bool:
# 任何状态机的核心都是建立如下的状态机模型
states = {
"start": {"SIGN":"sign1", "DIGIT":"digit1", "DOT":"dot1"},
"sign1": {"DIGIT":"digit1", "DOT":"dot1"},
"sign2": {"DIGIT":"D"},
"digit1": {"DIGIT":"digit1", "DOT":"dot2", "EXP":"exp", "END": True},
"digit2": {"DIGIT":"digit2", "EXP":"exp", "END": True},
"dot1": {"DIGIT":"digit2"}, # 前面没数字
"dot2": {"DIGIT":"digit2", "EXP":"exp", "END": True}, # 前面有数字
"exp": {"SIGN":"sign2", "DIGIT":"D"},
"D": {"DIGIT":"D", "END": True}
}
def get(ch):
if ch == ".": return "DOT"
elif ch in "+-": return "SIGN"
elif ch in "Ee": return "EXP"
elif ch.isdigit(): return "DIGIT"
state = "start"
for c in s:
state = states[state].get(get(c))
if not state: return False
return "END" in states[state]