/*
参考剑指offer,改动了一些小部分。
数值可以表示为 A[.[B]]e|E[C]
其中A 和C 可以带有正负号,B不能带有符号
A可以没有,B也可以没有,不过在'.'的情况下
在e|E ,B是必须有的,所以这就是在判断str[index]=='.' 和str[index]=='e'||
str[index]=='E'时是使用不同运算符的原因。
然后分解成两个函数小函数我觉得可读性强一点,毕竟代码给人看的,想看细节的同学
请移步剑指offer官方书籍。
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串
* @return bool布尔型
*/
bool isNumeric(string str) {
// write code here
if(str.empty()) return false;
size_t index=0;
bool numeric=scanInteger(str,index);
if(str[index]=='.'){
++index;
bool hasNumbers=scanUnsignedInteger(str,index);
numeric=hasNumbers || numeric;
}
if(str[index]=='e'|| str[index]=='E'){
++index;
numeric=numeric && scanInteger(str,index);
}
return numeric && (index==str.size());
}
bool scanInteger(string& str,size_t& index){
if(str[index]=='+'||str[index]=='-')
++index;
return scanUnsignedInteger(str,index);
}
bool scanUnsignedInteger(string& str,size_t& index){
size_t begin=index;
while(str[index]!='\0' && str[index]>='0'&& str[index]<='9')
++index;
return index>begin;
}
};