Valid Number @python

來源:互聯網
上載者:User

標籤:

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.