@ 剑指offer(python)表示数值的字符串

    xiaoxiao2022-06-27  200

    剑指offer刷题笔记53(python)

    题目描述

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

    思路

    在给出的可能出现的字符串中,有三个字符比较特殊,“±”,“e or E”,“.”,需要对着几种情况进行考虑:

    “±”只能出现在字符串首或者字符“e or E”后面,且不能出现在最后一位。“.”不能出现在字符串首,也不能出现在字符串尾部,也不能出现在字符“e or E”后面,且不能出现两次。“e or E”不能出现两次且不能出现在字符串尾部。除了0–9和上面三个字符,不能出现其他的字符。 在具体的实现过程中,由于“e or E”和“.”不能出现两次,那么我们可以设置两个表示这两个字符能否在出现的标志。

    代码

    # -*- coding:utf-8 -*- class Solution: # s字符串 def isNumeric(self, s): # 主要是dot和E不能随便出现 # write code here allowDot = True allowE = True for i in range(len(s)): if s[i] in "+-" and (i == 0 or s[i-1] in "Ee") and i != (len(s)-1): continue elif allowDot and s[i] == ".": allowDot = False # 若当前字符为“.”,那么后面就不能出现“.”了,修改标志为False,“eE”同理。 if i == 0 or i == (len(s) -1) or allowE == False: return False elif allowE and s[i] in "Ee": allowE = False if i == len(s)-1: return False elif s[i] not in "0123456789": # 最后验证是否出现了其他字符 return False return True

    最新回复(0)