Valid Number

https://leetcode.com/problems/valid-number/description/

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.

Thoughts

什么样是合法的数: 1. 首尾可以出现无数个空格 2. 第一个字符可以是"+/-" 3. 之后必须是数字或者".". 4. 之后可以是'e', 如果是'e'后面可以接"+/-" 5. 之后必须是数字. 像.3, -3., -3.e-2啥的都是合法的, 但'.'和'e2'之类的就不合法. 根据这些顺序的规则, 我们用hasDigit判断是否有数字, 如果遇到e就置为false, 后面再有数字置为true。最后判断是否i到了N且hasDigit。

Code

/*
 * @lc app=leetcode id=65 lang=cpp
 *
 * [65] Valid Number
 */
class Solution {
public:
    bool isNumber(string s) {
        const int N = s.size();
        int i = 0;
        // trim
        while (i < N && s[i] == ' ') ++i;
        // the sign
        if (i < N && (s[i] == '+' || s[i] == '-')) ++i;
        // digits until
        bool digit = false;
        while (i < N && (s[i] >= '0' && s[i] <= '9')) {
            digit = true;
            ++i;
        }
        // the dot
        if (i < N && s[i] == '.') ++i;
        // continue
        while (i < N && (s[i] >= '0' && s[i] <= '9')) {
            digit = true;
            ++i;
        }
        // 'e'
        if (i < N && s[i] == 'e' && digit) {
            digit = false;
            ++i;
            if (i < N && (s[i] == '+' || s[i] == '-')) ++i;
        }
        // continue
        while (i < N && (s[i] >= '0' && s[i] <= '9')) {
            digit = true;
            ++i;
        }
        // trim
        while (i < N && s[i] == ' ') ++i;
        return (i == N) && digit;
    }
};

Analysis

时间复杂度O(N).

Last updated