Concise and Intuitive Java code. Code explains.


  • 0
    M
    public class Solution {
        public String parseTernary(String expression) {
            Stack<Character> stack = new Stack<>();
            for (int i = expression.length() - 1; i >= 0; --i) { // Notice we start from right side so that the right expression will be evaluated first
                char c = expression.charAt(i);
                if (c == ':') {
                    if (expression.charAt(i-2) == '?') {
                        char cond = expression.charAt(i-3);
                        char left = expression.charAt(i-1);
                        char right = stack.pop();
                        stack.push(cond == 'T' ? left : right);
                        i = i - 3;
                    }
                } else if (c == '?') {
                    char left = stack.pop();
                    char right = stack.pop();
                    char cond = expression.charAt(i-1);
                    stack.push(cond == 'T' ? left : right);
                    i = i - 1;
                } else {
                    stack.push(c);
                }
            }
            return stack.pop() + "";
        }
    }
    

Log in to reply
 

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