[Java] From behind to front with stack / T : O(N), S: O(N)


  • 0
    J
    class Solution {
        public String parseTernary(String expression) {
            Stack<Character> st = new Stack<Character>();
            char[] chs = expression.toCharArray();
            
            for(int i = chs.length-1; i >= 0; i--){
                if(chs[i] == '?'){
                    char first = st.pop();
                    char second = st.pop();
                    
                    if(chs[i-1] == 'T'){
                        st.push(first);
                    } 
                    else{
                        st.push(second);
                    }
                    i -= 1;
                }
                else if(chs[i] != ':'){
                    st.push(chs[i]);
                }
            }
            return String.valueOf(st.pop());
        }
        
    }
    

Log in to reply
 

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