[LeetCode]题解(python):065-Valid Number

题目来源:

  https://leetcode.com/problems/valid-number/


题意分析:

  输入一个字符串,判断这个字符串表示的是不是一个有效的数字。比如:

  "0" => true
  " 0.1 " => true
  "abc" => false
  "1 a" => false
  "2e10" => true


题目思路:

  由于空格在两端不影响,所以首先将两端的空格去掉。判断开始是否数字,如果不是直接返回False,然后判断是否遇到'.'和‘e',然后判断'e'以后是否有’+‘,’-‘和’.'。


代码(Python):

  

 class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
begin,last =0,len(s) - 1
while begin <= last and s[begin] == ' ': begin += 1
while begin <= last and s[last] == ' ': last -= 1
if begin < last and (s[begin] == '+' or s[begin] == '-'): begin += 1
num,dot,exp = False,False,False
while begin <= last:
if s[begin] >= '' and s[begin] <= '':
num = True
elif s[begin] == '.':
if dot or exp:
return False
dot = True
elif s[begin] == 'e' or s[begin] =='E':
if exp or not num:
return False
exp,num = True,False
elif s[begin] =='+' or s[begin] == '-':
if begin == 0 or s[begin - 1] != 'e':
return False
else:
return False
begin += 1
return num

转载请注明出处:http://www.cnblogs.com/chruny/p/5028726.html

上一篇:asp下实现多条件模糊查询SQL语句


下一篇:hdu 5439(找规律)