Simple C++ recursive solution


  • 0
    B

    This algorithm was implemented with the following idea.

    1. If an expression has a condition, do recursion with 'true' expression or 'false' expression.
      If condition is false, it skips 'true' expression and moves to 'false' expression.
    2. If an expression doesn't have a condition, it returns the expression.
    class Solution {
    public:
        // skip 'true' expression
        int skipTrueExpr(string e, int i) {
            int expCnt = 1;
            while (i < e.length() && expCnt > 0) {
                if (e[i] == '?')
                    expCnt++;
                else if (e[i] == ':')
                    expCnt--;
                i++;
            }
            
            return i;
        }
    
        string parseTernary(string e, int i) {
            int start = i;
            for (; i < e.length() && e[i] != ':'; i++) {
                if (e[i] == '?')
                    return parseTernary(e, (e[i - 1] == 'T') ? i + 1 : skipTrueExpr(e, i + 1));
            }
            return e.substr(start, i - start);
        }
    
        string parseTernary(string expression) {
            return parseTernary(expression, 0);
        }
    };
    

Log in to reply
 

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