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~
  • 相关阅读:
    [YTU]_2917(Shape系列-3)
    c3p0-0.9.2.1.bin用于jdbc链接池
    C#加密解密DES字符串<转>
    Bechmarksql
    PHP中foreach有关引用的问题
    jqgrid 原理2
    jqggrid原理2
    jqgrid1原理
    JQgrid 入门
    搞开发真的是 坑太多了,
  • 原文地址:https://www.cnblogs.com/jkmiao/p/4399677.html
Copyright © 2011-2022 走看看