题目
Validate if a given string is numeric.
Some examples:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10” => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
思路
题目描述的数据格式很模糊
一开始考虑根据标准的科学计数格式检测,如: -20.122e-120
后来过不了发现漏了 ‘1.’ 以及 ‘.3’这种数据格式也符合要求,小数点前后都可以空,为了方便判断用计数器计算数据的位数
对字符串左到右一次扫描
① 跳过初始的空格和一个正负号(如果存在空格和正负)
② 计算e前面的数据位数,中间会检测一次小数点并跳过
③ 跳过e以及e后一位的正负号(如果存在e和正负),计算e后面指数位数
④ 跳过最后的空格
在②③④步骤中若数据位数小于1则会直接判断为不符合,若其中遇到‘.’或‘e’的位置或个数不对的情况,或者出现其他字符的情况,则停止遍历,只有最后能遍历到字符串的尾部说明其符合题目数据格式要求
代码
class Solution {
public:
bool isNumber(string s) {
//example +32.44e+43242
if (s.empty()) return false;
int i = 0, n_nm = 0;
while(s[i] == ' ') i++;//跳过空格
if(i < s.length() && s[i] == '+' || s[i] == '-') i++;
while(s[i] >= '0' && s[i] <= '9' && i < s.length()) {
n_nm++;
i++;
}
if(i < s.length() && s[i] == '.' ) {
i++;
while(s[i] >= '0' && s[i] <= '9' && i < s.length()) {
n_nm++;
i++;
}
}
if(n_nm < 1) return false;//'e'前面1位数都没有则不符合
if(i < s.length() && s[i] == 'e') {
i++;
if(i < s.length() && s[i] == '+' || s[i] == '-') i++;
n_nm = 0;
while(s[i] >= '0' && s[i] <= '9' && i < s.length()) {
n_nm++;
i++;
}
if(n_nm < 1) return false;//'e'后面1位数都没有则不符合
}
while(i < s.length() && s[i] == ' ') i++;
return i == s.length();
}
};