表示数值的字符串

题目:
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值