AC Java Solution using Stack and StringBuilder


  • 0
    public class Solution {
        public String parseTernary(String expression) {
            if (expression == null || expression.length() == 0) {
                return expression;
            }
            Stack<String> stack = new Stack<String>();
            boolean isCondition = false;
            StringBuilder sb = new StringBuilder();
            for (int i = expression.length() - 1; i >= 0; --i) {
                char c = expression.charAt(i);
                if (c == ':') {
                    if (sb.length() != 0) {
                        stack.push(sb.reverse().toString());
                    }
                    sb.delete(0, sb.length());
                } else if (isCondition && stack.size() >= 2 && (c == 'T' || c == 'F')) {
                    String exp1 = stack.pop();
                    String exp2 = stack.pop();
                    if (c == 'T') {
                        stack.push(exp1);
                    } else {
                        stack.push(exp2);
                    }
                    isCondition = false;
                } else if (c == '?'){
                    isCondition = true;
                    if (sb.length() != 0) {
                        stack.push(sb.reverse().toString());
                    }
                    sb.delete(0, sb.length());
                } else {
                    sb.append(c);
                }
            }
            return stack.isEmpty() ? "" : stack.peek();
        }
    }
    

Log in to reply
 

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