解法:
1. 要设计好问考官的问题。
2. 解法与LeetCode8非常相似,可将问题分为几个组成部分:
(1)开头的空格(可有可无)
(2)正负号(可有可无)
(3)数字
(4)e和e后的数字(可有可无)
(5)结尾的空格
推荐解法比我的方法简洁得多,可读性强,但分数却低了一些。原因是我的方法中“一言不合”就返回False,而推荐解法中是保存标志,到最后返回,所以时间和空间都消耗稍微多一些。
Python源码:
Runtime: 28 ms, faster than 27.33% of Python online submissions for Valid Number.
Memory Usage: 11.7 MB, less than 50.00% of Python online submissions for Valid Number.
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
i = 0
length = len(s)
while(i < length and s[i] == ' '):
i += 1
if(i < length and (s[i] == '+' or s[i] == '-')):
i += 1
isNumeric = False
while(i < length and s[i].isdigit()):
i += 1
isNumeric = True
if(i < length and s[i] == '.'):
i += 1
while(i < length and s[i].isdigit()):
i += 1
isNumeric = True
if isNumeric and i < length and s[i] == 'e':
i += 1
isNumeric = False
if(i < length and (s[i] == '+' or s[i] == '-')):
i += 1
while (i < length and s[i].isdigit()):
i += 1
isNumeric = True
while(i < length and s[i] == ' '):
i += 1
return isNumeric and i == length
我的心路:
从左向右遍历,每步考虑每步的情况。有很多种“合法”情况没有考虑到,花费了一些debug时间。时间复杂度,空间复杂度。
完成之后发现这道题是Hard!评分标准是需要问考官的问题多少吗?
Runtime: 20 ms, faster than 78.42% of Python online submissions for Valid Number.
Memory Usage: 11.6 MB, less than 100.00% of Python online submissions for Valid Number.
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
if s == '':
return False
i = 0
length = len(s)
num_left_dot = False
num_left_space = False
num_left_valid = False
while(i <= length -1 and s[i] == ' '):
i += 1
if i > length - 1:
return False
if (i < length - 1 and (s[i] == '+' or s[i] == '-')):
if not s[i+1].isdigit() and s[i+1] != '.':
return False
else:
i += 1
while(i <= length - 1 and (s[i].isdigit() or s[i] == '.')):
if s[i] == '.':
if ((i - 1 >= 0 and not s[i - 1].isdigit()) or (i - 1 < 0)) and \
((i + 1 <= length - 1 and not s[i + 1].isdigit()) or (i + 1 > length - 1)):
return False
if num_left_dot:
return False
else:
num_left_dot = True
i += 1
num_left_valid = True
while(i < length and s[i] == ' '):
i += 1
num_left_space = True
if (i < length - 1 and s[i] == 'e'):
if num_left_space:
return False
if not num_left_valid:
return False
if num_left_space:
return False
elif s[i+1] == '-' or s[i+1] == '+':
if i + 2 > length - 1 or not s[i+2].isdigit():
return False
else:
i += 1
elif not s[i+1].isdigit():
return False
i += 1
while(i <= length - 1 and s[i].isdigit()):
if num_left_space:
return False
i += 1
while(i <= length - 1):
if s[i] != ' ':
return False
i += 1
return True