Leetcode:65. Valid Number
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.
思路
- 这个题简直就是恶心。按照剑指offer上的思路来做,简直不要太坑。
代码
class Solution {
public:
bool isNumber(string s) {
int len = s.size();
if(len == 0) return false;
int i = 0;
while(i < len && s[i] == ' ') i++;
if(i < len && (s[i] == '+' || s[i] == '-'))
i++;
if(i == len) return false;
bool digit = false, digit2 = false;
if(s[i] >= '0' && s[i] <= '9'){
digit = true;
while(i < len && s[i] >= '0' && s[i] <= '9') i++;
}
bool isExpon = false, judge = false, isD = false;
if(i < len && s[i] == '.'){
isD = true;
i++;
while(i < len && s[i] >= '0' && s[i] <= '9'){
digit2 = true;
i++;
}
if(i < len && (s[i] == 'e' || s[i] == 'E')){
judge = true;
isExpon = isValidOfE(s, i, len);
}
while(i < len && s[i] == ' ')
i++;
}
else if(i < len && (s[i] == 'e' || s[i] == 'E')){
judge = true;
isExpon = isValidOfE(s, i, len);
}
while(i < len && s[i] == ' ')
i++;
if(i != len)
return false;
if(isD && !digit && !digit2)
return false;
if(judge){
if(!isExpon) return false;
return (digit || (isD && digit2));
}
return true;
}
bool isValidOfE(string& str, int &i, int len){
if(str[i] == 'e' || str[i] == 'E')
i++;
if(i < len && (str[i] == '-' || str[i] == '+'))
i++;
if(i == len) return false;
if(str[i] >= '0' && str[i] <= '9'){
while(i < len && (str[i] >= '0' && str[i] <= '9'))
i++;
return true;
}
else return false;
}
};