[Java] Stack solution


  • 1
    A
        public String parseTernary(String expression) {
    
            Stack<Character> stack = new Stack<>();
            for (int i = expression.length() - 1; i >= 0; --i) {
                char c = expression.charAt(i);
                if (c == ':')
                    continue;
                else if (c == '?') {
                    char left = stack.pop();
                    char right = stack.pop();
                    char condition = expression.charAt(i - 1);
                    stack.push(condition == 'T' ? left : right);
                    --i;
                } else {
                    stack.push(c);
                }
            }
            return stack.pop().toString();
        }
    

Log in to reply
 

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