65. Valid Number
Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
AC代码:
bool isNumber(string s)
{
int size=s.size();
if(size==0)
return false;
int start=0,end=size-1;
while(s[start]==' ')
{ start++; }
while(s[end]==' ')
{ end--; }
bool hasPoint=false,hasNum=false,hasE=false;
for(int i=start;i<=end;i++)
{
if(s[i]=='.')
{ if(hasPoint||hasE)
{
return false;
}
hasPoint=true;
}
else if(s[i]=='e')
{
if(hasE||!hasNum)
{ return false; }
hasE=true;
}
else if(s[i]<'0'||s[i]>'9')
{
if(i==start&&(s[i]=='+'||s[i]=='-'))
{ continue; }
else if(i>0&&s[i-1]=='e'&&(s[i]=='+'||s[i]=='-'))
{ continue; }
else{ return false; }
}
else { hasNum=true; }
}
if(s[end]=='e'||s[end]=='-'||s[end]=='+')
return false;
if(!hasNum&&hasPoint)
return false;
if(end==-1) return false;
return true;
}