65. Valid Number
Problem description:
Validate if a given string is numeric.
Some examples:
“0” => true
“ 0.1 “ => true
“abc” => false
“1 a” => false
“2e10” => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
Solution:
This is a problem to let you discuss with interviewer and implement the detail.
- skip the leading white spaces
- check the positive or negative sign is valid. if there’re two ‘+’ or ‘-‘, it should be invalid.
- To do so, simply skip the leading sign and count the number of digits and the number of points. A valid significant has no more than one point and at least one digit.
- check if the exponent part is valid. We do this if the significant is followed by ‘e’. Simply skip the leading sign and count the number of digits. A valid exponent contain at least one digit.
- skip the trailing white spaces. We must reach the ending ‘\0’ if the string is a valid number.
- White spaces: may have three cases
- leading white spaces, skip it
- trailing white space, skip it
- white spaces in the middle of string, invalid number
- Decimal point
- can only appear once, but can show in any position. “.3”, “1.e2”, “1.”
- can not showed after
e
. “1e.1”
example that can use1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25string s1 = "0"; // True
string s2 = " 0.1 "; // True
string s3 = "abc"; // False, not digit
string s4 = "1 a"; // False, because white space in the middle
string s5 = "2e10"; // True
string s6 = "-e10"; // False
string s7 = " 2e-9 "; // True
string s8 = "+e1"; // False
string s9 = "1+e"; // False
string s10 = " "; // False
string s11 = "e9"; // False
string s12 = "4e+"; // False
string s13 = " -."; // False
string s14 = "+.8"; // True
string s15 = " 005047e+6"; // True
string s16 = ".e1"; // False
string s17 = "3.e"; // False
string s18 = "3.e1"; // True
string s19 = "+1.e+5"; // True
string s20 = " -54.53061"; // True
string s21 = ". 1"; // False
1 | class Solution { |
time complexity: $O(n)$