Java Easy to Understand Without Stack


  • 0
    T

    Every time, we will evaluate the expression most right. So we use the position of '?' to get the expression. Then from the position of '?' we can easily get the condition and value, and then rebuild the expression, until we can not find '?'.

        public String parseTernary(String expression) {
            if (expression == null || expression.length() == 0) {
                return "";
            }
            StringBuilder builder = new StringBuilder();
            while (expression.lastIndexOf("?") != -1) {
                builder.setLength(0);
                int i = expression.lastIndexOf("?");
                boolean condition = expression.charAt(i - 1) == 'T' ? true : false;
                char value = condition == true ? expression.charAt(i + 1) : expression.charAt(i + 3);
                builder.append(expression.substring(0, i - 1)).append(value).append(expression.substring(i + 4));
                expression = builder.toString();
            }
            return expression;
        }
    

Log in to reply
 

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