Leetcode -- 65. 有效数字

验证给定的字符串是否为数字。

例如:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10” => true

说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。

其实这题不难,主要是上面的说明比较坑。。。

class Solution(object):
    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.strip()
        if (s.startswith(".") and s.endswith(".")) or s.__len__() == 0:
            return False
        try:
            float(s)
            return True
        except ValueError:
            pass
        if s.count(".") > 1 or s.count("e") > 1 or s.count("+") > 1:
            return False
        if s.find("e+") != -1 and not s.endswith("e+") and not s.startswith("e+"):
            return True
        if s.startswith("e") or s.endswith("e") or s.startswith(".e") or(s.find(".e") != -1 and not s[s.__len__()-1].isdigit()) or s.find("e.") != -1 or s.find("e") < s.find("."):
            return False
        elif s.find("e") != -1 and s.find("e") != 0 and not s.endswith("e"):
            s = s[:s.find("e")] + s[s.find("e")+1:]


        return s.isdigit()

猜你喜欢

转载自blog.csdn.net/ydonghao2/article/details/80149119