What about a Java Recursive Solution, 5ms


  • 0
    L

    The idea is to solve the problem level-by-level, which requires us to find the proper position of ":" and "?" that correctly format the expression.

        public String parseTernary(String expression) {
            if(expression.length() == 1) return expression;
            int indexQ = 0, indexC = 0;
            for(int i=0; i<expression.length(); i++){
                if(expression.charAt(i) == '?') {
                    indexQ = i;
                    break;
                }
            }
            int Q = 0;
            for(int i=indexQ+1; i<expression.length(); i++){
                if(expression.charAt(i) == '?') Q++;
                if(expression.charAt(i) == ':') Q--;
                if(Q < 0){
                    indexC = i;
                    break;
                }
            }
            if(expression.charAt(0) == 'T') return parseTernary(expression.substring(indexQ+1, indexC));
            else return parseTernary(expression.substring(indexC+1));
        }
    

Log in to reply
 

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