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

思路: 

# -*- coding:utf-8 -*-
class Solution:
    # s字符串
    def isNumeric(self, s):
        # write code here
        hasE=False
        sign=False
        decimal=False
        for i in range(0,len(s)):
            if s[i] == 'e' or s[i] == 'E':
                if i == 0: 
                    return False #指数符号前必须有整数
                if i == len(s)-1:
                    return False #e后面一定要接数字
                if hasE:
                    return False #不能同时存在两个e
                hasE = True
            elif s[i] == '+' or s[i] == '-':
                if not sign and i != 0 and not hasE: #第一次出现+''-'符号只能在第一个字符或者指数符号后
                    return False  
                if sign and not hasE:
                    return False  #第二出现'+''-'符号只能在指数符号后
                if i == len(s) - 1: 
                    return False  #'+''-'符号不能出现在最后一位上
                sign = True
            elif s[i] == '.': 
                # 小数点只能在e之前,小数点不能出现两次
                if hasE or decimal:
                    return False
                if i == len(s) - 1: 
                    return False  #小数点不能出现在最后一位上
                decimal = True
            elif s[i]<'0' or s[i]>'9': # 不合法字符
                return False
        return True

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/86350516