Intuition
A valid number has a fixed grammar: optional sign, a mantissa (integer or decimal), and an optional exponent. A single anchored regex captures it precisely.
Explanation
One grammar, one regex
^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$
[+-]?— optional sign.\d+\.?\d*— an integer or a decimal with digits before the dot (e.g.3,3.,3.5).\.\d+— a decimal with digits only after the dot (e.g..5).([eE][+-]?\d+)?— an optional exponent needing at least one digit.
The anchors ^ and $ force the whole string to match.
Worked example
"53.5e93" → mantissa 53.5, exponent e93 → true. "1e" → exponent has no digits → false.
Complexity
- Time: O(n).
- Space: O(1).
Implementation
class Solution {
public boolean isNumber(String s) {
return s.matches("[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?");
}
}