LeetCode Valid Number

LeetCode解题之Valid Number


原题

推断一个字符串是否是数值类型的。这里的数值类型除了一般要考虑的小数、正负数外还要考虑科学计数法e,如” -3.2e-23 “是数值类型的。

注意点:

  • 小数点前和后没有数字都是合法的
  • 科学计数法后面也能够是负数

样例:

输入: s = ” -3.2e-23 “

输出: True

解题思路

比較恶心的一道题,没有明白给出定义,给了一些样例。须要自己不断去尝试。首先要把前后的空字符给去掉。然后依次考虑符号、数字、小数点、数字。假设有这些中连续的几个,表示眼下是一个普通的数值。继续推断”e”(注意大写和小写都能够),接着推断符号、数字,假设e后面没有数字。那么这是一个不正常的科学类数值。最后依据三种情况来综合推断,要满足目标是一个数值类型。那么首先要保证e前面的数是正常的。假设有e的话,要保证它后面的数也是正常的。最后要保证整个字符串都已经遍历玩了,假设没有说明中间出现了一些异常的字符或者末尾多了一些多余的字符。

AC源代码

class Solution(object):
    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.strip()
        length = len(s)
        index = 0
        # Deal with symbol
        if index < length and (s[index] == '+' or s[index] == '-'):
            index += 1
        is_normal = False
        is_exp = True
        # Deal with digits in the front
        while index < length and s[index].isdigit():
            is_normal = True
            index += 1
        # Deal with dot ant digits behind it
        if index < length and s[index] == '.':
            index += 1
            while index < length and s[index].isdigit():
                is_normal = True
                index += 1
        # Deal with 'e' and number behind it
        if is_normal and index < length and (s[index] == 'e' or s[index] == 'E'):
            index += 1
            is_exp = False
            if index < length and (s[index] == '+' or s[index] == '-'):
                index += 1
            while index < length and s[index].isdigit():
                index += 1
                is_exp = True
        # Return true only deal with all the characters and the part in front of and behind 'e' are all ok
        return is_normal and is_exp and index == length


if __name__ == "__main__":
    assert Solution().isNumber("3.e-23") == True
    assert Solution().isNumber(".2e81") == True
    assert Solution().isNumber("2e10") == True
    assert Solution().isNumber(" 0.1") == True
    assert Solution().isNumber("1 b") == False
    assert Solution().isNumber("3-2") == False
    assert Solution().isNumber("abc") == False

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

原文地址:https://www.cnblogs.com/liguangsunls/p/7240774.html