65 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.

The Idea: I definitely view this problem as a valid interview question, but it's validity only comes through the interaction and conversation exchange between interviewer and interviewee. In an OJ setting, the problem is that the 'requirements' that you have to gather are in some cases, subjective, and you end up learning through trail and error in the end. My solution would be to have OJ specify a relatively exhaustive list of examples that the user can this use to formulate a good idea on what these requirements are.

An organized approach (1) to this problem would be to create a state transition diagram that captures all the valid states that can occur from one to another. A valid number is then just one that follows a traversal through this graph and terminates on a valid state.

Complexity: O(n) time where n is the length of the string, and O(1) space

class Solution:
    SM = \
    [{},
     {'blank': 1, 'digit': 3, 'sign': 2, 'dot': 4},
     {'digit': 3, 'dot': 4},
     {'digit': 3, 'blank': 9, 'e': 6, 'dot': 5},
     {'digit': 5},
     {'digit': 5, 'e': 6, 'blank': 9},
     {'sign': 7, 'digit': 8},
     {'digit': 8},
     {'digit': 8, 'blank': 9},
     {'blank': 9}]

    char_map = {'+': 'sign', '-': 'sign', '.': 'dot', 'e': 'e', ' ': 'blank'}
    end_states = {3, 5, 8, 9}

    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """

        # start here
        current_state = 1
        for c in s:
            # find what state next character takes us
            if c.isdigit():
                c = 'digit'
            elif c in Solution.char_map:
                c = Solution.char_map[c]
            else:
                return False

            # ensure that it is a valid state
            if c not in Solution.SM[current_state].keys():
                return False

            # enter that next state
            current_state = Solution.SM[current_state][c]

        # make sure we terminate at a valid state
        if current_state not in Solution.end_states:
            return False
        return True

Last updated