Question
Validate if a given string is numeric.
You may assume that each input would have exactly one solution.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Recursive Descent Parsing
By observing the samples above, we can draw an LL(1) grammar:
Number => Spaces,RealNumber,Exponent,Spaces
Exponent => Empty
=> ‘e’,Integer
Integer => ‘+’,RInteger
=> ‘-‘,RInteger
=> RInteger
RInteger => ‘0’,EInteger
…
=> ‘9’,EInteger
EInteger => Empty
=> ‘0’,EInteger
…
=> ‘9’,EInteger
RealNumber => ‘+’,RRealNumber
=> ‘-‘,RRealNumber
=> RRealNumber
Spaces => Empty
=> ‘ ‘,Spaces
- Time Complexity: O(n)
- Space Complexity: O(1)
Deterministic Finite Automata
By observing the samples above, we can draw a DFA.
The structure is shown in the code.
- Time Complexity: O(n)
- Space Complexity: O(1)
Finding law
By observing the samples above, we can find the law and solve it directly
- Time Complexity: O(n)
- Space Complexity: O(1)