A clear c++ solution


  • 2
    E
    class Solution {
        // Check if s[pos] is in `cset',if s[pos] in cset, move pos forward
        int parse_char(string &s,int &pos, const string &cset){
            if (pos < s.length() && cset.find(s[pos]) != -1){
                pos++;
                return 1;
            }
            return 0;
        }
        int parse_sig(string &s,int &pos){
            return parse_char(s,pos,"-+");
        }
        int parse_dot(string &s,int &pos){
            return parse_char(s,pos,".");
        }
        int parse_real(string &s,int &pos){
            // 1.1   1.    .1   1  are all valid
            int n1 = parse_int(s,pos);
            int n2 = parse_dot(s,pos);
            int n3 = parse_int(s,pos);
            if (n1 || (n2 && n3)) return 1;
            return 0;
        }
        int parse_e(string &s,int &pos){
            return parse_char(s,pos,"eE");
        }
        int parse_int(string &s,int &pos){
            // return 1 if at least 1 integer is consumed.
            if (parse_char(s,pos,"0123456789")){
                while (parse_char(s,pos,"0123456789")) ;
                return 1;
            }
            return 0;
        }
        int parse_space(string &s,int &pos){
            while (parse_char(s,pos," "));
            return 1;
        }
    public:
        bool isNumber(string s) {
            int pos = 0;
            parse_space(s,pos);
            parse_sig(s,pos);
            if (!parse_real(s,pos)) return 0;
            if (parse_e(s,pos)){
                parse_sig(s,pos);
                if (!parse_int(s,pos))
                    return 0;
            }
            parse_space(s,pos);
            return s.length() == pos;
        }
    };
    

    The idea is simple: try to consume the expected characters in each stage.


Log in to reply
 

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