Java solution, couple of different versions


  • 0
    V
    class Solution {
        public String parseTernary(String expression) {
            if (expression == null || expression.length() == 0 || expression.length() < 5) return expression;
            char[] ex = expression.toCharArray();
            int i = 0;
            String result = expression;
            if (ex[0] == 'T') {
                i = findBalancedIndex(ex, 2);
                result = parseTernary(expression.substring(2, i));
            } else {
                i = findBalancedIndex(ex, 2);
                result = parseTernary(expression.substring(i + 1));
            }
            
            return result;
        }
        
        int findBalancedIndex(char[] s, int start) {
            int diff = 0;
            while(start < s.length) {
                if (s[start] == ':') {
                    if (diff == 0) break;
                    else diff--;
                } else if (s[start] == '?') diff++;
                
                start++;
            }
            
            return start;
        }
    }
    
    class Solution {
        public String parseTernary(String expression) {
            if (expression == null || expression.length() == 0 || expression.length() < 5) return expression;
            
            char[] ex = expression.toCharArray();
            Stack<Character> stk = new Stack<>();
            for (int i = ex.length - 1; i >= 0; i--) {
                if (ex[i] == '?') {
                    char first = stk.pop();
                    stk.pop();
                    char second = stk.pop();
                    if (ex[i - 1] == 'T') stk.push(first);
                    else stk.push(second);
                    i--;
                } else {
                    stk.push(ex[i]);
                }
            }
            
            return "" + stk.pop();
        }
    }
    

Log in to reply
 

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