Follow these rules and get AC in one attempt


  • 0
    S

    Code is difficult to remember but the rule is not. OJ defines valid number as:

    1. Delete/omit leading and trailing spaces because they don't affect validity
    2. The string can only ends with digit or "."
    3. "e": can only appear once, must have numeric value before it
    4. ".": can only appear once, can only appear before "e" appears
    5. "+/-": can only appear in the beginning of the valid string or right after "e"
    6. Other chars like " " "a" are invalid
    7. The string contains at least one digit

    Here is code:

    class Solution {
    public:
        bool isNumber(string s) 
        {
            bool e = false, dot = false, numeric = false;
            int i = 0, j = s.size() - 1;
            // omit leading blanks
            for (; i < s.size() && s[i] == ' '; ++i);
            // if all blanks return false
            if (i == s.size()) return false;
            // omit trailing blanks
            for (; j >= 0 && s[j] == ' '; --j);
            // the string can only ends with digit or "."
            if (s[j] != '.' && !isdigit(s[j])) return false; 
            // "+/-": can appear in the beginning of the valid string
            if (s[i] == '+' || s[i] == '-') ++i; 
    
            for (; i <= j; ++i)
            {
                // at least one digit
                if (isdigit(s[i])) numeric = true; 
                // ".": can only appear once, can only appear before "e" appears
                else if (s[i] == '.')
                {
                    if (dot || e) return false;
                    dot = true;
                }
                // "e": can only appear once, must have numeric value before it
                else if (s[i] == 'e')
                {
                    if (e || !numeric) return false;
                    e = true;
                }
                // "+/-": can only appear right after "e"
                // we have checked once before entering the loop so here only the case for checking "e"
                else if (s[i] == '+' || s[i] == '-')
                {
                    if (s[i-1] != 'e') return false; 
                }
                // Other chars like " " "a" are invalid
                else return false;
            }
            return numeric && true;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.