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.
思路:综合考虑不同的情况,代码写得很丑,也花了很长时间,但此题真正牛逼的解法是状态机,看这里
class Solution {
public:
bool isNumber(string s) {
int n = s.size();
int start = 0;
int end = n - 1;
while (start < end&&(s[start]==' '||s[end]==' ')){ //去除左右的空格
if (s[start] == ' '&&start < end)
start++;
if (s[end] == ' '&&start < end)
end--;
}
cout << start << ' ' << end << endl;
int cnt1 = 0; //cnt1记录点的个数
int pos1 = -1;
int cnt2 = 0; //cnt2记录e的个数
int pos2 = -1;
int cnt3 = 0; //记录数字的数量
for (int i = start; i <= end; i++){
if (isdigit(s[i]))
cnt3++;
else if (s[i] == '.'){
cnt1++;
pos1 = i; //记录点出现的位置
if (cnt1>1)
return false;
if (pos2>0&&pos2<pos1) // e . 的情况
return false;
if ((i == start&&s[i + 1] == 'e') || (i == end&&s[i - 1] == 'e'))
return false;
}
else if (s[i] == 'e'){
cnt2++;
pos2 = i;
if (cnt2 > 1)
return false;
if (i == start || i == end)
return false;
if (!isdigit(s[i - 1])&& s[i - 1] != '.')
return false;
}
else if (s[i] == '+' || s[i] == '-'){
if (i == end)
return false;
if (i != start){
if (s[i - 1] != 'e' || !isdigit(s[i + 1]))
return false;
}
}
else
return false;
}
if (cnt3 == 0) //数字的数量为0
return false;
return true;
}
};