Link to the problem

The problem is here: https://leetcode-cn.com/problems/valid-number/

Problem description

Given a string s, check whether it is a valid representation of a number.

Idea & Implementation

Regex

This problem can be straightforwardly by using regular expressions. We may utilize the python package re. This is my simple implementation.

  1. class Solution:
  2. def isNumber(self, s: str) -> bool:
  3. valid_number = re.compile(r'[+-]?((\d+(\.\d*)?)|(\.\d+))([Ee][+-]?\d+)?$')
  4. m = valid_number.match(s)
  5. return m != None

Can learn more about the re package in Chinese here.

DFA

The Deterministic Finite Automaton (DFA) is a very basic and important idea. We can apply it here to solve this problem.

In the theory of computation, a branch of theoretical computer science, a deterministic finite automaton (DFA)—also known as deterministic finite acceptor) (DFA), deterministic finite-state machine (DFSM), or deterministic finite-state automaton (DFSA)—is a finite-state machine that accepts or rejects a given string) of symbols, by running through a state sequence uniquely determined by the string.

We need to first come up with the DFA for this problem. We have the following tokens:

  • **+/-**: the plus or minus sign
  • **E/e**: the English letter
  • **.**: the dot
  • **0-9**: the digits

Then one possible state transition diagram is like this:
dfa.png

Image is from leetcode-cn

With the above diagram, we can easily write out the code.