【LeetCode with Python】 Valid Number

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/valid-number/
题目类型:
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/41628867

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts aconst char * argument, please click the reload buttonto reset your code definition.


class Solution:
    def getType(self, ch):
        if '^' == ch:
            return 0
        elif ' ' == ch:
            return 1
        elif '+' == ch or '-' == ch:
            return 2
        elif ch >= '0' and ch <= '9':
            return 3
        elif '.' == ch:
            return 4
        elif 'e' == ch:
            return 5
        elif '$' == ch:
            return 6
        else:
            return 7

    def getMap(self):
        map = (
               (0,     0,      1,      4,      2,     -1,     -1,     -1),      # 0: ^ / space
               (-1,     -1,     -1,     4,     2,     -1,    -1,     -1),      # 1: + / -
               (-1,     -1,     -1,     3,     -1,    -1,    -1,     -1),       # 2: .
               (-1,     10,    -1,     3,      -1,     7,    11,     -1),       # 3: num
               (-1,     10,    -1,     4,      5,      7,   11,    -1),       # 4: num
               (-1,     10,    -1,     6,     -1,     7,     11,     -1),      # 5: .
               (-1,     10,    -1,     6,      -1,     7,    11,     -1),       # 6: num
               (-1,     -1,    8,       9,      -1,    -1,    -1,     -1),       # 7: e
               (-1,     -1,    -1,     9,      -1,     -1,    -1,     -1),       # 8: + / 1
               (-1,     10,    -1,     9,      -1,    -1,     11,    -1),       # 9: num
               (-1,     10,    -1,    -1,     -1,     -1,    11,     -1)       # 10: space
               )
        return map

    # @param s, a string
    # @return a boolean
    def isNumber(self, s):
        map = self.getMap()
        state = 0
        after_s = "^" + s + "$"
        for ch in after_s:
            type = self.getType(ch)
            state = map[state][type]
            if -1 == state:
                break

        return 11 == state

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值