题目:
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
思路一:
穷举
代码:
class Solution:
# s字符串
def isNumeric(self, s):
if not s: return False
if 'e' in s:
if s.count('e') > 1: return False
else:
i = s.index('e')
if i == len(s)-1: return False
return self.helper1(s[:i]) and self.helper2(s[i+1:])
if 'E' in s:
if s.count('E') > 1: return False
else:
i = s.index('E')
if i == len(s)-1: return False
return self.helper1(s[:i]) and self.helper2(s[i+1:])
return self.helper1(s)
def helper1(self, s):
arr = ['0','1','2','3','4','5','6','7','8','9','.']
if s.count('.') > 1: return False
for i in s[1:]:
if i not in arr: return False
if s[0] != '+' and s[0] != '-' and s[0] not in arr:
return False
else: return True
def helper2(self, s):
arr = ['0','1','2','3','4','5','6','7','8','9']
for i in s[1:]:
if i not in arr: return False
if s[0] != '+' and s[0] != '-' and s[0] not in arr:
return False
else: return True
思路二:
巧妙
代码:
class Solution:
# s字符串
def isNumeric(self, s):
arr = ['0','1','2','3','4','5','6','7','8','9']
e, decimal = 0, 0
for i in range(len(s)):
if s[i] in arr: continue
elif s[i] == '+' or s[i] == '-':
if i != 0 and s[i-1] != 'e' and s[i-1] != 'E': return False
elif s[i] == 'e' or s[i] == 'E':
if i == 0 or i == len(s)-1 or e: return False
e = 1
elif s[i] == '.':
if decimal or i == len(s)-1 or s[i+1] == 'e' or s[i+1] == 'E' or e: return False
decimal = 1
else: return False
return True