clueless coding // TODO: be smarter

LeetCode Ternary Expression Parser: CPP Solution



TL;DR Code Solution



string parseTernary(string expression) {

    stack<char> stac;

    for (int i = expression.length(); i >= 0; i--) {

        if (!stac.empty() && stac.top() == '?') {
            stac.pop();
            char t = stac.top();
            stac.pop();
            char f = stac.top();
            stac.pop();

            if (expression[i] == 'T') {
                stac.push(t);
            }
            else {
                stac.push(f);
            }

        }
        else if (expression[i] == ':') {
            continue;
        }
        else {
            stac.push(expression[i]);
        }

    }

    return string(1, stac.top());


}