[leetcode] 65. Valid Number 解题报告

题目链接:https://leetcode.com/problems/valid-number/

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.


思路:这种字符串处理的题目烦的很,corner case 太多而且题目说的也不清楚,需要注意的是下面几种case (.54343)这种数据是合法的,(.)这个数据是不合法的,323e这种数据是不合法的,e后面需要跟数字,并且还可能有符号.开头结尾可能有空格.

我们可以设置两个计数器,一个用来测试字符串是否能够按照规定的字符走完,另一个用于标记是否出现了非法的case,比如e后面没有跟数据,或者e不能出现在首位,因为比如:1.2e+12这种是科学计数法,表示1.2*(10^12),所以e之前必须有数据.

代码如下:

class Solution {
public:
    bool isNumber(string s) {
        int i = 0, cnt = 0;
        while(s[i] == ' ') i++;
        while(s[i] == '+' || s[i] == '-') i++;
        while(s[i] >='0' && s[i] <= '9') i++, cnt++;
        if(s[i] == '.') i++;
        while(s[i] >= '0' && s[i] <= '9') i++, cnt++;
        if(cnt ==0) return false;
        if(s[i] == 'e')
        {
            int k = 0;
            i++;
            if(s[i] == '+' || s[i] == '-') i++;
            while(s[i] >= '0' && s[i] <= '9') i++, k++;
            if(k == 0) return false;
        }
        while(s[i]==' ') i++;
        return i == s.size();
    }
};
参考:https://leetcode.com/discuss/88730/rainbow-concise-clearer-implementaiton-detailed-comments

你可能感兴趣的:(LeetCode,Math,String)