链接:https://leetcode.com/problems/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.
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.
这道题条条框框是在太多了,各种情况。。不过简略来说,正确的做法应该是:
1、熟悉数字的表述规则
2、对输入的数字首先进行必要的检测,是否有abc或者中间空格等非法字符
3、将e前面和e后面分开计算!e前面允许有小数点形式的,e后面不允许有小数点形式的
4、数字的形式一般是 可以有正负号,如果是0.几,可以省略0,“.”前面不一定有数字,点后面一定有数字。。等等
class Solution {
public:
bool isNumber(string s) {
while(!s.empty() && s[0]==' ') s.erase(s.begin());
while(!s.empty() && s[s.size()-1]==' ') s.erase(s.end()-1);
if(s.empty()) return false;
if(s.find('e')==-1) return check(s,true);
else return check(s.substr(0,s.find('e')),true) && check(s.substr(s.find('e')+1),false);
}
bool check(string s, bool point)
{
//为空肯定失败
if(s.empty()) return false;
int i=0;
bool num=false;
//是否存在符号,十号的话要先跳过,且只能有一个。。如果符号过后就没有数字了,那么也是非法的
if(s[i]=='+' || s[i]=='-') i++;
if(i==s.size()) return false;
//整数位置的数据
while(i<s.length() && s[i]<='9' && s[i]>='0')
{
i++;
num=true;
}
//如果不允许出现小数点,那么这个过程就必须匹配结束,不然就是失败
if(i<s.size() && point==false)
return false;
//允许小数点,下一位必须为小数点
//小数点后,必须遇到e或结束
if(i<s.size() && s[i]=='.')
{
bool num2=false;
i++;
while(i<s.size() && s[i]<='9' && s[i]>='0')
{
i++;
num2=true;
}
if(num2==false && num==false)
return false;
}
return i==s.size();
}
};