One pass solution using flags


  • 0
    B
    bool isNumber(string s) {
            //flags
            bool allow_sign = true;         
            bool allow_dot = true;          
            bool allow_e = true;
            
            bool found_e_left = false;
            bool found_e_right = true;      //true, if no e,
            
            //remove tailing spaces
            int e = s.size() - 1;
            while (e >= 0 && s[e] == ' ') {
                --e;
            }
            
            //remove heading spaces
            int b = 0;
            while (b < e && s[b] == ' ') {
                ++b;
            }
    
            
            while (b <= e) {
                if (s[b] == '+' || s[b] == '-') {
                    if (!allow_sign) {
                        return false;
                    }
                    allow_sign = false;
                } else if (s[b] == '.') {
                    if (!allow_dot) {
                        return false;
                    }
                    allow_dot = false;
                    allow_sign = false;
                } else if (s[b] == 'e') {
                    if (!found_e_left || !allow_e) {
                        return false;
                    }
                    found_e_right = false;
                    allow_e = false;
                    allow_dot = false;
                    allow_sign = true;          //reset allow_sign to true after found e
                } else if (s[b] >= '0' && s[b] <= '9') {    //numbers;
                    if (!found_e_left) {    //no e left found
                        found_e_left = true;
                    } else if (!allow_e)  {    //found e
                        found_e_right = true;
                    }
                    allow_sign = false;
                } else {     //invalid char
                    return false;
                }
                ++b;
            }
            return found_e_left && found_e_right;
    }
    

Log in to reply
 

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