public class Solution {
public String parseTernary(String expression) {
if (expression == null || expression.length() == 0) return null;
Stack<Character> stack = new Stack<Character>();
for (int i = expression.length() - 1; i >= 0; i--) {
char c = expression.charAt(i);
if (!stack.isEmpty() && stack.peek() == '?') {
stack.pop(); // pop '?'
char firstValue = stack.pop();
stack.pop(); // pop ':'
char secondValue = stack.pop();
if (c == 'T') {
stack.push(firstValue);
} else {
stack.push(secondValue);
}
} else {
stack.push(c);
}
}
return String.valueOf(stack.peek());
}
}