172. Is It a Number

A form field must accept only decimal numbers. Decide whether the string s is a valid one. A valid number has, in this order: an optional sign (+ or -); a main part, which is either digits, or digits with one dot and digits on one or both sides of the dot (so at least one digit must exist next to it); and then an optional exponent. The exponent is the letter e or E, an optional sign, and one or more digits, with no dot in it.

Return true if the whole string follows these rules and false otherwise. Spaces, other letters, a second dot or a second sign make a string invalid. For example, 5. and .5e1 are valid, but . and e5 are not.

Example 1

Input:
s = "-7.25e-3"
Output:
true
Explanation:

A sign, digits with a dot, and an exponent with its own sign and digits: valid.

Example 2

Input:
s = "3e+"
Output:
false
Explanation:

The exponent has a sign but no digits, so the string is not a valid number.

Constraints

1 ≤ s.length ≤ 105

s contains letters, digits, signs, dots and spaces

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…