C++ O(n) 9 lines straightforward solution with comments


  • 1
    class Solution {
    private:
        // Returns evaluation for expression.substr(start, ...)
        // and advance start along the way
        string parse(string& expression, int& start) {      
            string firstC = expression.substr(start, 1);    // record the first char as string
            start += 2;                                     // advance 2 chars to skip next '?' or ':'
            
            // simply a digit, 'T' or 'F' for answer
            if (start - 1 >= expression.length() || expression[start - 1] != '?') { return firstC; }    
            
            // Evaluate based on T/F, and advance start along the way
            string trueAns = parse(expression, start), falseAns = parse(expression, start);
            return firstC == "T" ? trueAns : falseAns;
        }
        
    public:
        string parseTernary(string expression) {
            int start = 0;
            return parse(expression, start);
        }
    };
    

Log in to reply
 

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