C++ recursive descendant parser. string and stringstream two version


  • 0
    C

    use string + pointer

        string parse(string& s, int& i) {
            if(s[i] == 'T' || s[i] == 'F') {
                char sign = s[i];
                i++;
                if(s[i] == '?') {
                    i++;
                    string op1 = parse(s, i);
                    if(s[i] == ':') i++;
                    string op2 = parse(s, i);
                    if(sign == 'T') return op1;
                    else return op2;
                } 
                else return string(1, sign);
            }
            else {
                return string(1, s[i++]);            
            }
        }
        string parseTernary(string expression) {
            int i = 0;
            return parse(expression, i);
        }
    
    

    use stringstream

        string parse(stringstream& ss) {   
            char tmp = '.';
            ss >> tmp;
            if(tmp == 'T' || tmp == 'F') {
                char sign = tmp;
                if(ss.peek() == '?') {
                    ss >> tmp; // skip '?'
                    string op1 = parse(ss);
                    ss >> tmp;  
                    string op2 = parse(ss); 
                    if(sign == 'T') return op1;
                    else return op2;
                } 
                else return string(1, sign);
            }
            else {
                return string(1, tmp);            
            }
        }
        string parseTernary(string expression) {
            stringstream ss(expression);
            return parse(ss);
        }
    
    

Log in to reply
 

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