Hard
, Array/String
判斷給定字符串是否為數(shù)字
Example:
'0' True
'1.' True
'abc' False
P.S.: 1.忽略開始和結(jié)尾的空格
2.請注意指數(shù)形式'1e10'也是數(shù)字
Solution
此題與atoi類似惜互。 先要去掉開始空格料祠,然后處理‘+’和‘-’腺逛, 然后處理數(shù)字,最后是最后的空格全肮。數(shù)字的處理涉及小數(shù)和指數(shù).下面的解法通過移動指針一步一步解決問題奶栖。
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
```