/*
In order to pick out useful "?" and ":", we can always begin with the last "?" and the first ":" after the chosen "?".
Therefore, directly seek for the last "?" (or you can simply put all "?" into a stack) and update the string depending on T or F until no more "?"s.
*/
public class Solution {
public String parseTernary(String expression) {
int len = expression.length();
Deque<Character> stack = new ArrayDeque<Character>();
for(int i = len - 1; i >=0; i--) {
char temp = expression.charAt(i);
if(!stack.isEmpty() && stack.peek() == '?') {
stack.pop(); // ?
char first = stack.pop();
stack.pop();// :
char second = stack.pop();
if(temp == 'T') {
stack.push(first);
} else {
stack.push(second);
}
} else {
stack.push(temp);
}
}
return String.valueOf(stack.peek());
}
}