题解 | #表示数值的字符串#
表示数值的字符串
http://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
求解步骤:
1.对单独的"."进行处理;
if str == ".":
return False
2.去除字符串中的空格,组成新字符串(定义filter函数过滤);
def is_space(self, s):
return s != ' '
str_rm_space = filter(self.is_space, str)
new_str = ""
for s in list(str_rm_space):
new_str += s
3.字符串中出现两个及以上"."进行处理, 用str.split('.')划分即可判断包含几个".";
# 检查小数点个数
dot_check = new_str.split('.')
if len(dot_check) > 2:
return False
4.利用正则表达式匹配数字和小数
# 匹配数字和小数,包括小数
if re.match('^(\+|\-|)(\d+)(\.(\d+|))?$', new_str):
return True
if re.match('^(\+|\-|)(\.\d+)$', new_str):
return True
5.利用正则表达式匹配科学计数法数字
if re.match('^(\+|\-|)(\d+)(\.\d+)(e|E)(\+|\-|)(\d+)(\.\d+)?$', new_str):
return True
if re.match('^(\+|\-|)(\d+)(\.)?(e|E)(\-|)(\d+)(\.\d+)?$', new_str):
return True
整体代码如下
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param str string字符串
# @return bool布尔型
#
class Solution:
def is_space(self, s):
return s != ' '
def isNumeric(self , str: str) -> bool:
# write code here
# 去除空格
if str == ".":
return False
str_rm_space = filter(self.is_space, str)
new_str = ""
for s in list(str_rm_space):
new_str += s
# 检查小数点个数
dot_check = new_str.split('.')
if len(dot_check) > 2:
return False
import re
# 匹配数字和小数,包括小数
if re.match('^(\+|\-|)(\d+)(\.(\d+|))?$', new_str):
return True
if re.match('^(\+|\-|)(\.\d+)$', new_str):
return True
# 匹配科学计数法数字
if re.match('^(\+|\-|)(\d+)(\.\d+)(e|E)(\+|\-|)(\d+)(\.\d+)?$', new_str):
return True
if re.match('^(\+|\-|)(\d+)(\.)?(e|E)(\-|)(\d+)(\.\d+)?$', new_str):
return True
return False