代码非常有条理,不加注释应该页能看懂吧...小数判断会利用到整数判断,科学计数法判断需要用到整数判断和小数判断,所以新建了3个函数。
class Solution:
def isNumeric(self , str: str) -> bool:
# write code here
str = str.strip()
if str.count('e') + str.count('E') > 1:
return False
elif str.count('e') + str.count('E') == 1:
return self.checkSci(str)
if str.count('.') > 1:
return False
elif str.count('.') == 1:
return self.checkDeci(str)
return self.checkInt(str)
def checkInt(self, str):
if len(str)>0 and str[0] in ['+','-']:
str = str[1:]
if len(str) == 0:
return False
for i in str:
if i not in ['1','2','3','4','5','6','7','8','9','0']:
return False
return True
def checkDeci(self, str):
if len(str)>0 and str[0] in ['+','-']:
str = str[1:]
dotPos = str.find('.')
if dotPos == -1:
return False
preStr = str[:dotPos]
postStr = str[dotPos+1:]
if self.checkInt(preStr):
if self.checkInt(postStr) or len(postStr) == 0:
return True
if self.checkInt(postStr):
if len(preStr) == 0:
return True
return False
def checkSci(self, str):
ePos = str.find('e')
if ePos == -1:
ePos = str.find('E')
preStr = str[:ePos]
postStr = str[ePos+1:]
if self.checkInt(preStr) or self.checkDeci(preStr):
if self.checkInt(postStr):
return True
return False