Ternary Expression Parser

medium stack recursion string

Problem

Given a string representing arbitrarily nested 'T?...:...' ternary expressions, return the result. Operands are digits 0–9 or T/F.

Inputexpr = "T?2:3"
Output"2"
T → take the value before ':' (= 2).

def parse_ternary(expr):
    stack = []
    for ch in reversed(expr):
        if stack and stack[-1] == "?":
            stack.pop()  # ?
            t = stack.pop()
            stack.pop()  # :
            f = stack.pop()
            stack.append(t if ch == "T" else f)
        else:
            stack.append(ch)
    return stack[-1]
function parseTernary(expr) {
  const stack = [];
  for (let i = expr.length - 1; i >= 0; i--) {
    const ch = expr[i];
    if (stack.length && stack[stack.length - 1] === "?") {
      stack.pop();
      const t = stack.pop();
      stack.pop();
      const f = stack.pop();
      stack.push(ch === "T" ? t : f);
    } else {
      stack.push(ch);
    }
  }
  return stack[stack.length - 1];
}
class Solution {
    public String parseTernary(String expr) {
        Deque<Character> stack = new ArrayDeque<>();
        for (int i = expr.length() - 1; i >= 0; i--) {
            char ch = expr.charAt(i);
            if (!stack.isEmpty() && stack.peek() == '?') {
                stack.pop();
                char t = stack.pop();
                stack.pop();
                char f = stack.pop();
                stack.push(ch == 'T' ? t : f);
            } else stack.push(ch);
        }
        return String.valueOf(stack.peek());
    }
}
string parseTernary(string expr) {
    stack<char> st;
    for (int i = expr.size() - 1; i >= 0; i--) {
        char ch = expr[i];
        if (!st.empty() && st.top() == '?') {
            st.pop();
            char t = st.top(); st.pop();
            st.pop();
            char f = st.top(); st.pop();
            st.push(ch == 'T' ? t : f);
        } else st.push(ch);
    }
    return string(1, st.top());
}
Time: O(n) Space: O(n)