//这道题目最麻烦的是:
// 1.判断空格应该出现在哪里?
// 2.什么样子的数字是有效数字。
class Solution {
public:
int scanDigits(string s, int start, bool& flag)//扫描数字,flag标志是否有扫描到数字,返回string指针的索引
{
while(start < s.size() && s[start] >= '0' && s[start] <= '9')
{
flag = true;
start++;
}
return start;
}
int scanSpace(string s, int start, bool& flag)
{
while(s[start] == ' ')
{
start++;
flag = true;
}
return start;
}
int isExponential(string s, int start, bool& flag)
{
if(s[start] == '+' || s[start] == '-')
start++;
if(start == s.size())
return false;
bool tmp = false;
start = scanDigits(s, start, tmp);
if(!tmp)
{
flag = false;
}
else
{
start = scanSpace(s, start, tmp);
flag = (start == s.size())?true: false;
}
return start;
}
bool isNumber(string s) {
int i = 0;
while(i<s.size() && s[i] == ' ')
i++;
if(i == s.size())
return false;
//正负号
if(s[i] == '+' || s[i] == '-')
i++;
bool bdigit = false;
i = scanDigits(s, i, bdigit);
bool bspace = false;
i = scanSpace(s, i, bspace);
if(i == s.size())
return true;
bool flag = true;
if(i < s.size() && s[i] =='.')
{
i++;
if(bdigit && bspace)
return false;
i = scanDigits(s, i, bdigit);
bspace = false;
i = scanSpace(s, i, bspace);
if(bdigit && i == s.size())
return true;
if(bdigit == false)
return false;
if(bdigit && !bspace&& i < s.size() && (s[i] == 'e' || s[i] == 'E'))
i = isExponential(s, i+1, flag);
}
else if(bdigit && !bspace && (s[i] == 'e' || s[i] == 'E'))
i = isExponential(s, i+1, flag);
else
flag = false;
return flag &&(i == s.size());
}
};
LeetCode || Valid Number
最新推荐文章于 2023-07-17 04:23:40 发布