凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 65. Valid Number

分类:algorithm| 发布时间:2017-03-21 08:50:00


题目

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.

题意

判断一个字符串是否是否是合法的数值。

解法

class Solution {
public:
    bool isNumber(string s) {
        const char *str = s.c_str();
        while (*str == ' ') ++str;
        if (!skipNum(str)) return false;
        if (*str == 'e' || *str == 'E') {
            ++str;
            if (!skipNum(str, true)) return false;
        }

        while (*str == ' ') ++str;
        return *str == '\0';
    }

    bool skipNum(const char *&str, bool integerOnly = false) {
        if (*str == '+' || *str == '-') ++str;
        const char *in_str = str, *in_str2 = str;
        // skip num
        while (*str) {
            if (*str >= '0' && *str <= '9') {
                ++str;
            } else {
                break;
            }
        }

        if (integerOnly)
            return in_str != str;

        // skip dot and follow num
        if (*str == '.') {
            ++str;
            in_str2 = str;
            while (*str) {
                if (*str >= '0' && *str <= '9') {
                    ++str;
                } else {
                    break;
                }
            }
        }

        return (in_str == str) || (str == in_str2 && in_str2 - in_str == 1) ? false : true;
    }
};