Easy and short JAVA solution + Explanation


  • 0
    M

    We start from the last "?" and first ":" that follows it and evaluate the expression of 5 chars that encompasses them. We substitute the result in the string and recurse till we get a string of length 1, and return it.

     String eval(String exp){
            if(exp.charAt(0)=='F')
             return exp.charAt(4)+"";
            return exp.charAt(2)+"";
        }
        public String parseTernary(String exp){
            if(exp.length()<=1) return exp;
            int last=0;
            for(int i=0;i<exp.length();i++) if(exp.charAt(i)=='?') last=i;
            String prev = ((last-1)==0)?"":exp.substring(0,last-1);
            String mid = eval(exp.substring(last-1, last+4));
            String  next = exp.substring(last+4, exp.length());
            return parseTernary(prev+mid+next);
        }

Log in to reply
 

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