zoukankan      html  css  js  c++  java
  • Valid Number @python

    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 string
    11     # @return a boolean
    12     def isNumber(self, s):
    13         transition_table = [[-1,  0,  3,  1,  2, -1],     # next states for state 0
    14                             [-1,  8, -1,  1,  4,  5],     # next states for state 1
    15                             [-1, -1, -1,  4, -1, -1],     # next states for state 2
    16                             [-1, -1, -1,  1,  2, -1],     # next states for state 3
    17                             [-1,  8, -1,  4, -1,  5],     # next states for state 4
    18                             [-1, -1,  6,  7, -1, -1],     # next states for state 5
    19                             [-1, -1, -1,  7, -1, -1],     # next states for state 6
    20                             [-1,  8, -1,  7, -1, -1],     # next states for state 7
    21                             [-1,  8, -1, -1, -1, -1]]     # next states for state 8
    22                             
    23         state = 0
    24         for char in s:
    25             inputType = InputType.INVALID
    26             if char.isspace():
    27                 inputType = InputType.SPACE;
    28             elif char == '+' or char == '-':
    29                 inputType = InputType.SIGN
    30             elif char in '0123456789':
    31                 inputType =InputType.DIGIT
    32             elif char  == '.':
    33                     inputType = InputType.DOT
    34             elif char == 'e' or char =='E':
    35                 inputType = InputType.EXPONENT
    36                 
    37             state = transition_table[state][inputType]
    38             if state == -1:
    39                 return False
    40         return state==1 or state==4 or state ==7 or state==8
    41     
    42     def isNumber2(self,s):
    43         import re
    44         return bool(re.match("^s*[+-]?((d+(.d*)?)|.d+)([eE][+-]?d+)?s*$",s))
    View Code
    每天一小步,人生一大步!Good luck~
  • 相关阅读:
    perf-stat
    perf原理
    ubuntu中Docker的安装与使用
    NVM相关手册及新特性理解
    #2018BIT软件工程基础#结对项目:四则运算题目生成
    #2018BIT软件工程基础#个人项目:数独
    第一篇博文:自我介绍&新学期展望
    越早明白这些道理,越能少走一些弯路
    把知识连接起来就是创意
    【翻译】24款界面精美的免费UI工具包
  • 原文地址:https://www.cnblogs.com/jkmiao/p/4399677.html
Copyright © 2011-2022 走看看