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) 来获得相关源码。