leetcode算法学习(20)——表示数值的字符串

表示数值的字符串

  • 题目描述
  • 方法一:正则表达式
    • 思路
    • 代码
  • 方法二:条件判断
    • 思路
    • 代码

题目描述

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

方法一:正则表达式

思路

  • 符号"+" 或 " -“必须出现在首位或"e” 或 "E"的后面
  • 小数点"."前后可以无数字
  • “e” 或 “E"之后不能出现小数点”."

代码

import re
class Solution:
    def isNumber(self, s: str) -> bool:
        s=s.strip()
        pattern=r'^(([+-]?\.\d+([eE][+-]?\d+)?)|([+-]?\d+(\.(\d+)?)?([eE][+-]?\d+)?))$'
        return True if re.match(pattern,s) else False

方法二:条件判断

思路

  • 空格只能出现在首尾,出现在中间一定是非法的
  • 正负号只能出现在两个地方,第一个地方是整数的最前面。第二个位置是 e 后面,表示指数的正负。如果出现在其它位置也一定是非法的
  • 数字,数字没有进行特别的判断,多位数中,首位可为0
  • e 只能出现一次,并且 e 之后一定要有数字才是合法的, 12e 这种也是非法的
  • 小数点,由于 e 之后的指数一定是整数,所以小数点最多只能出现一次,并且一定要在 e 之前。所以如果之前出现过小数点或者是 e,再次出现小数点就是非法的

代码

class Solution:
    def isNumber(self, s: str) -> bool:
        s = s.strip()
        numbers = [str(i) for i in range(10)]
        n=len(s)
        # 用四个标记记录是否出现过 e 、小数点、数字和 e 之后的数字
        hasE, hasDot, hasNum, hasNumaftere = False, False, False, False

        for i in range(n):
            c=s[i]
            if c in numbers:
                hasNum=True
                hasNumaftere=True#先设置为True,当出现e时再设置为False,e之后出现num时则为True
            elif c in {'+','-'}:
                if i>0 and s[i-1]!='e':return False
            elif c=='.':
                if hasDot or hasE:return False
                hasDot=True
            elif c=='e':
                if hasE or not hasNum:return False
                hasE=True
                hasNumaftere=False
            else:return False
        return hasNum and hasNumaftere

你可能感兴趣的:(LeetCode算法)