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

来源:互联网 发布:编程软件cimit怎么样 编辑:程序博客网 时间:2024/06/05 03:22

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

# -*- 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


原创粉丝点击