Recursive solution, not the best complexity wise, but its fine


  • -1
    J

    '''
    public class Solution {
    public String parseTernary(String expression) {
    int split = expression.indexOf(":");
    if(split == -1){
    return expression;
    }
    int stack = 0;
    int i = 0;
    for(; i < expression.length(); ++i){
    char c = expression.charAt(i);
    if(c == '?') stack++;
    if(c == ':'){
    stack--;
    if(stack == 0)
    break;
    }
    }
    split = i;
    if(expression.charAt(0) == 'T'){
    return parseTernary(expression.substring(2, split));
    }else{
    return parseTernary(expression.substring(split + 1, expression.length()));
    }
    }
    }
    ''''


Log in to reply
 

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