验证给定的字符串是否可以解释为十进制数字。
例如:
“0” => true
" 0.1 " => true
“abc” => false
“1 a” => false
“2e10” => true
" -90e3 " => true
" 1e" => false
“e3” => false
" 6e-1" => true
" 99e2.5 " => false
“53.5e93” => true
" --6 " => false
“-+3” => false
“95a54e53” => false
说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。这里给出一份可能存在于有效十进制数字中的字符列表:
数字 0-9
指数 - “e”
正/负号 - “+”/"-"
小数点 - “.”
当然,在输入中,这些字符的上下文也很重要。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
class Solution {
public:
bool isInt(string& s, int& index) { // 判断是不是带有正负号的整数
if (index < s.size() && (s[index] == '-' || s[index] == '+')) index++;
return isUnsigned(s, index);
}
bool isUnsigned(string& s, int& index) { // 判断无符号整数
int pre = index;
while (index < s.size()) {
if (s[index] >= '0' && s[index] <= '9') index++;
else break;
}
return index > pre;
}
bool isNumber(string s) {
if (s.empty()) return false;
int index = 0;
while (index < s.size() && s[index] == ' ') index++; // 去掉前面的空格
bool ans = isInt(s, index);
if (index < s.size() && s[index] == '.') {
index++;
ans = isUnsigned(s, index) || ans; // 如果有小数点,只有前后都没有数字才不对
}
if (index < s.size() && s[index] == 'e') {
index++;
ans = isInt(s, index) && ans; // 如果出现指数e,则e的前后都必须要有整数
}
while (index < s.size() && s[index] == ' ') index++; // 去掉后面的空格
return ans && index == s.size();
}
};