my 9-line java 5 ms beats 92% no stack


  • 0
    public String parseTernary(String expression) {
            int len = expression.length();
            if(len < 2) return expression;
            int j = 2, countQ = 1;
            while(countQ > 0 && ++j < len) {
                if(expression.charAt(j) == '?') countQ++;
                else if(expression.charAt(j) == ':') countQ--;   //make j the index of ':' to pair the first'?'
            }
            if(expression.charAt(0) == 'T') return parseTernary(expression.substring(2,j));
            else return parseTernary(expression.substring(j + 1));
        }

Log in to reply
 

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