65 Valid Number
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.
class Solution {
public:
string parse(string s) {
int n = s.size(), i = 0, j, k;
while ( i < n ) {
if ( s[i] != ' ' ) break;
i++;
}
j = i;
while ( j < n ) {
if ( s[j] == ' ') break;
j++;
}
k = j;
while ( k < n ) {
if ( s[k] != ' ' ) break;
k++;
}
if ( k != n ) return "";
return s.substr(i, j-i);
}
string abstract(string s) {
int n = s.size(), i = 0;
string res = "";
while ( i < n ) {
if ( s[i] - '0' < 0 or s[i] - '0' > 9 ) res += s[i];
if ( s[i] - '0' >= 0 and s[i] - '0' <= 9 ) {
if ( res.size() == 0 or res[res.size()-1] != '0' ) res += '0';
}
i += 1;
}
return res;
}
bool isNumber(string s) {
// integer(positive, negative), decimal (0.5, .5, and 5. both counts), 1e-5, 1e05
// prefix spaces and trailing spaces are allowed
s = parse(s);
if ( s == "" ) return false;
string res = abstract(s);
string part1[3] = {"", "+", "-"};
string part2[4] = {"0", "0.0", ".0", "0."};
string part3[4] = {"", "e0", "e+0", "e-0"};
for ( int i1 = 0; i1 < 3; i1++ ) {
for ( int i2 = 0; i2 < 4; i2++ ) {
for ( int i3 = 0; i3 < 4; i3++ ) {
if ( res == part1[i1] + part2[i2] + part3[i3] ) return true;
}
}
}
return false;
}
};
Notes
- Parsing the string by removing spaces. If it splits into more than 1 part, it is not a valid number.
- Convert the string to an abstract form, using
'0'
to represent digit(s), and keep all the non-digit character. - The valid abstract form can be enumerated. Note the trick of using part1, part2 and part3 for comparison.