剑指Offer:表示数值的字符串

个人感觉这种题目用正则表达式匹配最简单,也就两三行代码就能解决,但是呢,好像并不能充分锻炼我们的逻辑思维能力,这个问题本身不难,但边界条件,特殊输入很多,要一一考虑清楚,下面给出一个一种一种情况考虑排除的解法,有点繁琐,但有注释,整体逻辑还是很清晰的。

# -*- coding:utf-8 -*-
class Solution:
    # s字符串
    def isNumeric(self, s):
        # write code here
        length = len(s)
        if length == 0:
            return False
        index = 0
        #如果开头有正负号,后移一位
        if s[index] == '+' or s[index] == '-':
            index += 1
        #如果只有正负号,也返回False
        if index >= length:
            return False
        #正负号后面只能是数字,后移直到不是数字
        while (index< length and s[index] >= '0' and s[index] <= '9'):
            index += 1
        #如果以数字结束,则是数值
        if index == length:
            return True
        #否则接下来要么是点,要么是e或者E
        else:
            #如果是点,后移一位
            if s[index] == '.':
                index += 1
                while (index< length and s[index] >= '0' and s[index] <= '9'):
                    index += 1
                #此时即是小数,返回True
                if index == length:
                    return True
                else:
                    #小数后面接科学计算法,判断科学计算法的合理性
                    if (index < length and s[index] == 'e' or s[index] == 'E'):
                        index += 1
                    if (index < length and s[index] == '+' or s[index] == '-'):
                        index += 1
                    while (index< length and s[index] >= '0' and s[index] <= '9'):
                        index += 1
                    if index == length:
                        return True
                    else:
                        return False
                    #如果前面不是小数,后面直接接科学计算法
            elif (s[index] == 'e' or s[index] == 'E'):
                index += 1
                if index == length:
                    return False
                elif (s[index] == '+' or s[index] == '-'):
                    index += 1
                while (index < length and s[index] >= '0' and s[index] <= '9'):
                    index += 1
                if index == length:
                    return True
                else:
                    return False
            #如果不包含在上述考虑的情况,直接返回False
            else:
                return False


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值