easy java solution. recursion


  • 0
    W
    public String parseTernary(String expression) {
        char[] ss = expression.toCharArray();
        if(ss.length == 1) {
            return expression;
        }
        int count = 0;
        int i;
        for(i = 0; i < ss.length; i++) {
            if(ss[i] != '?' && ss[i] != ':')
                continue;
            if(ss[i] == '?')
                count++;
            else if(ss[i] == ':')
                count--;
            if(count == 0) {
                break;
            }
        }
        if(ss[0] == 'T') {
            return parseTernary(expression.substring(2, i));
        } else {
            return parseTernary(expression.substring(i+1, ss.length));
        }
    }

Log in to reply
 

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