標籤:
Valid Number
Validate if a given string is numeric.
Some examples:
"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
直接上代碼,特別是解法二,引入 re 模組匹配,很精簡強大!
1 class InputType: 2 INVALID = 0 3 SPACE = 1 4 SIGN =2 5 DIGIT =3 6 DOT = 4 7 EXPONENT =5 8 9 class Solution:10 # @param s, a string11 # @return a boolean12 def isNumber(self, s):13 transition_table = [[-1, 0, 3, 1, 2, -1], # next states for state 014 [-1, 8, -1, 1, 4, 5], # next states for state 115 [-1, -1, -1, 4, -1, -1], # next states for state 216 [-1, -1, -1, 1, 2, -1], # next states for state 317 [-1, 8, -1, 4, -1, 5], # next states for state 418 [-1, -1, 6, 7, -1, -1], # next states for state 519 [-1, -1, -1, 7, -1, -1], # next states for state 620 [-1, 8, -1, 7, -1, -1], # next states for state 721 [-1, 8, -1, -1, -1, -1]] # next states for state 822 23 state = 024 for char in s:25 inputType = InputType.INVALID26 if char.isspace():27 inputType = InputType.SPACE;28 elif char == ‘+‘ or char == ‘-‘:29 inputType = InputType.SIGN30 elif char in ‘0123456789‘:31 inputType =InputType.DIGIT32 elif char == ‘.‘:33 inputType = InputType.DOT34 elif char == ‘e‘ or char ==‘E‘:35 inputType = InputType.EXPONENT36 37 state = transition_table[state][inputType]38 if state == -1:39 return False40 return state==1 or state==4 or state ==7 or state==841 42 def isNumber2(self,s):43 import re44 return bool(re.match("^\s*[\+\-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?\d+)?\s*$",s))
View Code
Valid Number @python