Hard
, Array/String
判断给定字符串是否为数字
Example:
'0' True
'1.' True
'abc' False
P.S.: 1.忽略开始和结尾的空格
2.请注意指数形式'1e10'也是数字
Solution
此题与atoi类似。 先要去掉开始空格,然后处理‘+’和‘-’, 然后处理数字,最后是最后的空格。数字的处理涉及小数和指数.下面的解法通过移动指针一步一步解决问题。
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s)==0: return False
i = 0
while i < len(s) and s[i] == ' ':
i += 1
if i < len(s) and s[i] in '+-':
i += 1
isNumeric = False
while i < len(s) and s[i].isdigit():
i +=1
isNumeric = True
if i < len(s) and s[i] == '.':
i+=1
while i < len(s) and s[i].isdigit():
i +=1
isNumeric = True
if isNumeric and i < len(s) and s[i] == 'e':
i+=1
isNumeric=False
if i<len(s) and s[i] in '+-':
i+=1
while i<len(s) and s[i].isdigit():
i+=1
isNumeric=True
while i < len(s) and s[i] == ' ':
i+=1
return isNumeric and i == len(s)
```
如果使用python,可以作弊,
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
try:
float(s)
except ValueError:
return False
else:
return True
```