Java 38 ms easy solution from front to end


  • 0
    R
    public class Solution439 {
        public String parseTernary(String expression) {
            if(expression == null || expression.length() == 0) return "";
            Stack<Character> st = new Stack<>();
            char[] ccc = expression.toCharArray();
            st.push(ccc[0]);
            for(int i = 1; i<ccc.length; i++) {
                if(Character.isLetterOrDigit(ccc[i])) {
                    if(st.peek() == ':' && (i == ccc.length-1 || ccc[i+1] == ':')) {
                        char c = ccc[i];
                        while(!st.isEmpty() && st.peek() == ':') {
                            st.pop();
                            char c3 = st.pop();
                            st.pop();
                            char c1 = st.pop();
                            if(c1 == 'T') c = c3;
                        }
                        st.push(c);
                    } else {
                        st.push(ccc[i]);
                    }
                } else {
                    st.push(ccc[i]);
                }
            }
            return st.peek() + "";
        }
    }
    

Log in to reply
 

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