整个思路如下图:
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
if s.find('e') != -1:
s1 = s[0:s.find('e')]
s2 = s[s.find('e')+1:]
#先处理'e'后字符串(整数)
if self.isInteger(s2) == False:
return False
else:
#对'e'前字符串处理
if s1.find('.') == -1:
return self.isInteger(s1)
else:
return self.isDecimal(s1)
elif s.find('E') != -1:
s1 = s[0:s.find('E')]
s2 = s[s.find('E')+1:]
#先处理'E'后字符串(整数)
if self.isInteger(s2) == False:
return False
else:
#对'E'前字符串处理
if s1.find('.') == -1:
return self.isInteger(s1)
else:
return self.isDecimal(s1)
else:
if s.find('.') == -1:
return self.isInteger(s)
else:
return self.isDecimal(s)
def isInteger(self, s, op = True):
#op代表是否允许带符号位
if s.find('.') == -1 and len(s) >= 1:
#不含小数点
if op == True and (s[0] == '-' or s[0] == '+'):
if len(s) == 1:
return False
#去掉第一个符号位
s = s[1:]
#检查s是否包含数字以外的非法字符
for char in s:
if char>='0' and char<='9':
continue
else:
return False
return True
else:
return False
def isDecimal(self, s):
dot = s.find('.')
if len(s)>=2:
#至少包含'.'和一位数字
if s.find('-') != -1 and s.find('-') < dot:
#符号在'.'前
if s[0] != '-':
#但符号不是第一位
return False
else:
s=s[1:]
dot -= 1
elif s.find('+') != -1 and s.find('+') < dot:
#符号在'.'前
if s[0] != '+':
#但符号不是第一位
return False
else:
s=s[1:]
dot -= 1
#以上去除合法的符号位(第一位)
if len(s) <= 1:
#此时字符串只有'.'
return False
for index in range(len(s)):
if index == dot:
#跳过第一个小数点
continue
else:
char = s[index]
if char >= '0' and char <= '9':
continue
else:
return False
return True
else:
return False
部分代码解释
写了两个子函数类内自定义函数:判断是否为整数、判断是否为小数
几个特殊测试用例‘+.’
‘.’
‘.1’
‘.-’



