题目描述:
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
思路1:
Python实现1:
// An highlighted block
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
try:
p = float(s)
return True
except:
return False
思路2:
python实现2:
// An highlighted block
import re
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
return re.match(r"^[\+\-]?[0-9]*(\.[0-9]*)?([eE][\+\-]?[0-9]+)?$", s)
#return re.match(r"^[\+\-]?([0]+|[1-9][0-9]*)(\.[0-9]*)?([eE][\+\-]?[0-9]+)?$", s)
思路3:
Python实现3:
// An highlighted block
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if s is None or len(s) == 0:
return False
# 是否有e
hasE = False
# 是否有小数
isDecimal = False
# 是否有+-符号
hasSign = False
for i in range(len(s)):
# 如果有e,只能有一个e且不能是最后一个
if s[i] == "e" or s[i] == "E":
if hasE or i == len(s) - 1:
return False
hasE = True
# 小数点不能重复出现或和e共线
elif s[i] == ".":
if hasE or isDecimal:
return False
isDecimal = True
elif s[i] == "-" or s[i] == "+":
# 重复出现符号时,必须跟在e后面
if hasSign and s[i - 1] != "e" and s[i - 1] != "E":
return False
# 重复出现符号时,必须跟在e后面
if not hasSign and i > 0 and s[i - 1] != "e" and s[i - 1] != "E":
return False
hasSign = True
elif s[i] < "0" or s[i] > "9":
return False
return True
原文:https://blog.csdn.net/yurenguowang/article/details/80588294