Valid Number

题目描述

Validate if a given string is numeric.

Some examples:

  • "0" => true
  • " 0.1 " => true
  • "abc" => false
  • "1 a" => false
  • "2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

解题方法

  • 应该只能最多有一个.
  • 检查是否有e,如果有分为两部分分别check, 后面的部分不应该有.
  • 检查是否有符号+ or -

Solution

class Solution(object):
    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.strip()

        if not s:
            return False

        if s[-1] == "e":
            return False

        arr = s.split("e")
        if len(arr) < 0 or len(arr) > 2:
            return False

        valid = self.check(arr[0], False)

        if len(arr) == 2 and valid:
            return self.check(arr[1], True)

        return valid


    def check(self, s, hasDot):
        if len(s) == 0:
            return False
        if s[0] == "+" or s[0] == "-":
            s = s[1:]
        # check if anything left after sign
        if len(s) == 0:
            return False
        if s == ".":
            return False
        for i in range(len(s)):
            if s[i] == ".":
                if hasDot:
                    return False
                hasDot = True
            elif s[i] not in "0123456789":
                return False

        return True

Reference