Clear Stack Java Solution


  • 0
    public class Solution {
        public String parseTernary(String expression) {
            if (expression == null || expression.length() < 5) return "";
            Stack<Character> stack = new Stack<>();
            int n = expression.length();
            for (int i = n - 1; i >= 0; i--) {
                char c = expression.charAt(i);
                if (Character.isDigit(c)) {
                    stack.push(c);
                }
                else if (c == 'T' || c == 'F') {
                    if (i < n - 1 && expression.charAt(i + 1) == '?') {
                        char val1 = stack.pop();
                        char val2 = stack.pop();
                        stack.push(c == 'T' ? val1 : val2);
                    } else {
                        stack.push(c);
                    }
                }
            }
            return String.valueOf(stack.peek());
        }
    }
    

Log in to reply
 

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