解题思路
代码比较长,但是很简单
「设计模式」中的访问者模式
使用一个类管理匹配,检查匹配状态即可
65. 有效数字
代码
class Solution:
def isNumber(self, s: str) -> bool:
mn = MatchNumber(s)
mn.match()
return mn.is_match()
class MatchNumber:
def __init__(self, s):
self.s = s
self.index = 0
self.fail = False
def match(self):
self.match_number()
x = self.match_exp()
if x:
self.match_int()
def is_match(self):
return not self.fail and self.index == len(self.s)
def match_number(self):
self.match_sign(False)
x = self.match_digits(False)
self.match_point(False)
self.match_digits(not x)
def match_int(self):
self.match_sign(False)
self.match_digits(True)
def match_sign(self, force=False):
if self.index < len(self.s) and self.s[self.index] in '-+':
self.index += 1
return True
elif force:
self.fail = True
def match_point(self, force=False):
if self.index < len(self.s) and self.s[self.index] == '.':
self.index += 1
return True
elif force:
self.fail = True
def match_digits(self, force=False):
idx = self.index
if force and self.index >= len(self.s):
self.fail = True
elif force and not self.s[self.index].isdigit():
self.fail = True
else:
while self.index < len(self.s) and self.s[self.index].isdigit():
self.index += 1
return idx != self.index
def match_exp(self, force=False):
if self.index < len(self.s) and self.s[self.index] in 'eE':
self.index += 1
return True
elif force:
self.fail = True
效果图
网友评论