C++ Simple Solution, Concise Code


  • 0
    class Solution {
        bool isOperation(char c) {
            return c == '?' || c == ':';
        }
    public:
        string parseTernary(string expression) {
            stack<char> ob, op;
            int n = (int)expression.size(), i = 0;
            while (i < n) {
                if (isOperation(expression[i])) {
                    op.push(expression[i]);
                } else { // objects
                    ob.push(expression[i]);
                    // find a legal expression
                    while (op.size() && op.top() == ':' && (i == n - 1 || expression[i + 1] != '?')) {
                        // a ? b : c
                        char a, b, c;
                        c = ob.top(), ob.pop();
                        b = ob.top(), ob.pop();
                        a = ob.top(), ob.pop();
                        op.pop(), op.pop();
                        if (a == 'T')
                            ob.push(b);
                        else
                            ob.push(c);
                    }
                }
                i++;
            }
            string res(1, ob.top());
            return res;
        }
    };
    

Log in to reply
 

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