题目来源:
https://leetcode.com/problems/valid-number/
题意分析:
输入一个字符串,判断这个字符串表示的是不是一个有效的数字。比如:
"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
题目思路:
由于空格在两端不影响,所以首先将两端的空格去掉。判断开始是否数字,如果不是直接返回False,然后判断是否遇到‘.‘和‘e‘,然后判断‘e‘以后是否有’+‘,’-‘和’.‘。
代码(Python):
1 class Solution(object): 2 def isNumber(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 begin,last =0,len(s) - 1 8 while begin <= last and s[begin] == ‘ ‘: begin += 1 9 while begin <= last and s[last] == ‘ ‘: last -= 1 10 if begin < last and (s[begin] == ‘+‘ or s[begin] == ‘-‘): begin += 1 11 num,dot,exp = False,False,False 12 while begin <= last: 13 if s[begin] >= ‘0‘ and s[begin] <= ‘9‘: 14 num = True 15 elif s[begin] == ‘.‘: 16 if dot or exp: 17 return False 18 dot = True 19 elif s[begin] == ‘e‘ or s[begin] ==‘E‘: 20 if exp or not num: 21 return False 22 exp,num = True,False 23 elif s[begin] ==‘+‘ or s[begin] == ‘-‘: 24 if begin == 0 or s[begin - 1] != ‘e‘: 25 return False 26 else: 27 return False 28 begin += 1 29 return num 30
转载请注明出处:http://www.cnblogs.com/chruny/p/5028726.html
时间: 2024-10-15 15:31:54