Intuitive commented Java solution

  • 2

    Any suggestion is greatly appreciated.

    Since the input is promised to be valid, life is much easier
    Use a stack, check from the end of the string to the front.
    As long as the next char is not '?', push it to the stack.
    If we see a '?', check the next char(left of '?' in the string), 
        pop the top 3 elements from the stack.
        if the next char is T
            push the first element of the 3 elements back to stack
            pusht the 3rd element of the 3 elements back to stack
    pop the only item left in the stack
    public class Solution {
        public String parseTernary(String expression) {
            if(expression == null || expression.length() == 0) return "";
            Stack<Character> s= new Stack<Character>();
            for(int i = expression.length() - 1; i > 0; i--){
                char element = expression.charAt(i);
                if(element != '?'){
                    char first = s.pop();
                    char second = s.pop();
                    if(expression.charAt(i-1) == 'T'){
            return ""+s.pop();

  • 0

    Great Idea! How did you come up with the thought of only comparing on '?' ?
    I thought about dealing with expression based on '?' and ':'

Log in to reply

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