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.
class Solution:def isNumber(self, s: str) -> bool:valid_number = re.compile(r'[+-]?((\d+(\.\d*)?)|(\.\d+))([Ee][+-]?\d+)?$')m = valid_number.match(s)return m != None
Can learn more about the
repackage 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:
Image is from leetcode-cn
With the above diagram, we can easily write out the code.
