Java, parse from tail to left, easy to understand


  • 0
    D
    public class Solution {
        public String parseTernary(String expression) 
        {
            Stack<Character> st = new Stack<>();
            // arr used to store one valid ternary expression
            // can also no need this char[], but this make code easier to understand
            char[] arr = new char[5];
            
            st.push(expression.charAt(expression.length() - 1));
            for (int i = expression.length() - 2; i >= 0; i--)
            {
                char c = expression.charAt(i);
                char pre = expression.charAt(i + 1);
                if (pre == '?')
                {
                    arr[0] = c;
                    for (int j = 1; j < 5; j++) { arr[j] = st.pop(); }
                    st.push(parse(arr));
                }
                else
                {
                    st.push(c);
                }
            }
            
            return "" + st.pop();
            
        }
        
        // parse ternary expression and return the result
        private char parse(char[] arr)
        {
            // the len of arr is always 5
            if (arr[0] == 'T') return arr[2];
            return arr[4];
        }
    }
    

Log in to reply
 

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