Easy to understand java solution


  • 1
    Z
    public class Solution {
        public String parseTernary(String expression) {
            if(expression.length() < 2)return expression;
            int count = 0;
            int pos = 0;
            for(int i = 2; i < expression.length(); i++){
                if(expression.charAt(i) == '?')count ++;
                if(expression.charAt(i) == ':')count --;
                if(count == -1){
                    pos = i;
                    break;
                }
            }
            if(expression.charAt(0) == 'T'){
                return parseTernary(expression.substring(2, pos));
            }else{
                return parseTernary(expression.substring(pos+1));
            }
        }
    }
    

Log in to reply
 

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