Easy understand recursion solution in Java.


  • 1
    H

    public static String parseTernary(String expression) {
    if(!expression.contains(":")) return expression;
    char c = expression.charAt(0);
    int i = 2;
    int count = 1;
    while (true ){
    if(expression.charAt(i) == '?') count++;
    else if(expression.charAt(i) == ':') count--;
    if(count == 0) break;
    i++;
    }
    if(c == 'T') return parseTernary(expression.substring(2,i));
    else return parseTernary(expression.substring(i+1,expression.length()));
    }


Log in to reply
 

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