剑指 Offer 20. 表示数值的字符串
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、"-1E-16"、“0123"都表示数值,但"12e”、“1a3.14”、“1.2.3”、"±5"及"12e+5.4"都不是。
首先,我们可以看到,对于一个字符串,可能存在小数点,正负号,指数符号,数值。
并且在字符串的开头和末尾部分还可能有若干个空格。因此,对于一个字符串,首先要略过开头和末尾的空格。
bool isNumber(string s) {
int n=s.size();
int index=-1;
bool hasDot= false,hasE= false,hasOp=false,hasNum= false;
while(index<n && s[++index]==' ');//开头可能含有若干个空格
while(index<n)
{
if('0'<=s[index]&&s[index]<='9')//如果当前字符串为 Num,令 hasNum=true
hasNum=true;
else if(s[index]=='e'||s[index]=='E')//如果当前字符串为 E或者 e,令 hasE=true
{
if(hasE||!hasNum)//如果此前未出现数字就出现了 E或者第二次出现 E,则不合法
return false;
//对于 E 后面的字符串重新考虑
hasE=true;
hasOp=false;
hasDot=false;
hasNum=false;
}else if(s[index]=='+'||s[index]=='-')//当前字符为正负号
{
if(hasOp||hasNum||hasDot)
return false;
}else if(s[index]=='.')//当前字符为.
{
if(hasDot||hasE)
return false;
hasDot=true;
}else if(s[index]==' ')//当前字符为空格,则跳出循环
{
break;
} else{
return false;
}
++index;
}
while(index<n &&s[++index]==' ');//末尾可能含有若干个空格
return hasNum &&index==n;
}