My solution in python


  • 0
    H
    class Solution:
    # @param s, a string
    # @return a boolean
    def isNumber(self, s):
        def movState(a, state, validChar):
            for k in validChar[state].keys():
                if a in k:
                    return VALID_CHAR[state][k]
            return -1
    
        BEFORE_NUM, ENTER_SIGN, ENTER_NUM, ENTER_FLOAT_I, ENTER_FLOAT_II, ENTER_SCI_I, ENTER_SCI_II, LEAVE_NUM = range(0, 8)
        VALID_CHAR = {
            BEFORE_NUM : {
                " " : BEFORE_NUM,
                "+-" : ENTER_SIGN,
                "." : ENTER_FLOAT_I,
                "0123456789" : ENTER_NUM,
            },
            ENTER_SIGN : {
                "0123456789" : ENTER_NUM,
                "." : ENTER_FLOAT_I,
            },
            ENTER_NUM : {
                "0123456789" : ENTER_NUM,
                "eE" : ENTER_SCI_I,
                "." : ENTER_FLOAT_II,
                " " : LEAVE_NUM,
            },
            ENTER_FLOAT_I : {
                "0123456789" : ENTER_FLOAT_II,
            },
            ENTER_FLOAT_II : {
                "0123456789" : ENTER_FLOAT_II,
                "eE" : ENTER_SCI_I,
                " " : LEAVE_NUM,
            },
            ENTER_SCI_I : {
                "0123456789" : ENTER_SCI_II,
                "+-" : ENTER_SCI_I,
            },
            ENTER_SCI_II : {
                "0123456789" : ENTER_SCI_II,
                " " : LEAVE_NUM,
            },
            LEAVE_NUM : {
                " " : LEAVE_NUM,
            }
        }
    
        VALID_STAT = [ENTER_NUM, ENTER_FLOAT_II, ENTER_SCI_II, LEAVE_NUM]
        state, i = BEFORE_NUM, 0
    
        while i < len(s):
            state = movState(s[i], state, VALID_CHAR)
            if state == -1:
                return False
            i += 1
    
        if state in VALID_STAT:
            return True
        return False

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.