Java fast, easy to understand solution


  • 0
        public String parseTernary(String expression) {
            if (expression.length() == 1) {
                return expression;
            }
            
            char condition = expression.charAt(0);
            int count = 0, i = 1;      // find the match ':' for the first '?'
            for (; i < expression.length(); i++) {
                if (expression.charAt(i) == '?') {
                    count++;
                }
                if (expression.charAt(i) == ':') {
                    count--;
                }
                if (count == 0)     break;
            }
            
            if (condition == 'T') {
                return parseTernary(expression.substring(2, i));
            } else {
                return parseTernary(expression.substring(i+1));
            }
        }
    

Log in to reply
 

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