剑指offer 53. 表示数值的字符串

题目描述

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。

思路:

这道题有点取巧了,直接利用float强转,可得到答案。
当然也有其他方法,如也可以引入正则表达式进行匹配。

My Answer:

# -*- coding:utf-8 -*-
class Solution:
    # s字符串
    def isNumeric(self, s):
        # write code here
        try:
            return float(s)
        except:
            return 0

补充一种通用的解题思路:
首先,检测科学计数法中的标准 ‘e’,然后切分后前后两部分判定是否符合要求,具体可见代码。

Python version:

# -*- coding:utf-8 -*-
class Solution:
    # s字符串
    def isNumeric(self, s):
        # write code here
        if not s:
            return False
        aList = [w.lower() for w in s]
        if 'e' in aList:
            index = aList.index('e')
            front = aList[:index]
            behind = aList[index+1:]
            if '.' in behind or len(behind) == 0:
                return False
            isFrond = self.scanDigit(front)
            isBehind = self.scanDigit(behind)
            return isFrond and isBehind
        else:
            isNum = self.scanDigit(aList)
            return isNum
    
    def scanDigittwo(self, alist):
        dotNum = 0
        allowVal = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '.', 'e']
        for index,count in alist:
            if count not in allowVal:
                return False
            if count == '.':
                dotNum += 1
            if count in '+-' and index != 0:
                return False
        if dotNum > 1:
            return False
        return True

    def scanDigit(self, alist):
        dotNum = 0
        allowVal = [str(i) for i in range(10)] + ['+', '-', '.', 'e']
        for i in range(len(alist)):
            if alist[i] not in allowVal:
                return False
            if alist[i] == '.':
                dotNum += 1
            if alist[i] in '+-' and i != 0:
                return False
        if dotNum > 1:
            return False
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值