Valid Number -- leetcode

来源:互联网 发布:飞狐主力资金指标源码 编辑:程序博客网 时间:2024/06/18 10:43

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.




class Solution {public:    bool isNumber(string s) {        int i = 0;        for (; s[i] == ' '; i++) {}                if (s[i] == '+' || s[i] == '-')            i++;                int n_num = 0, n_dot = 0;        for (; s[i] >= '0' && s[i] <= '9' || s[i] == '.'; i++)            s[i] == '.' ? n_dot++ : n_num++;                    if (!n_num || n_dot > 1)            return false;                    if (s[i] == 'e') {            i++;            if (s[i] == '+' || s[i] == '-')                i++;                        n_num = 0;            for (; s[i] >= '0' && s[i] <= '9'; i++)                n_num++;                            if (!n_num)                return false;        }                for (; s[i] == ' '; i++) {}                return !s[i];    }};


1. 跳过前导空格

2. 跳过符号+-

3. 统计数字和小数点的个数。合理的数字是小数点个数不能超过1个,数字不少于1个。

4. 检查指数部分。

4.1 跳过符号+-

4.2 统计数字个数。合理的数字个数至少为1个。

5. 跳过结尾空格

6. 此时当遇到字符串结束符。 若不是,则不是一个合法的数字。


此算法优点,比较直观易懂。



算法参考自:

https://leetcode.com/discuss/9013/a-simple-solution-in-cpp

0 0
原创粉丝点击