Java O(n) one pass w/o stack


  • 0
    D
    public class Solution {
        public String parseTernary(String expression) {
            if (expression == null || expression.length() < 5) {
                throw new IllegalArgumentException("");
            }
            
            StringBuilder sb = new StringBuilder(expression);
            while (true) {
                int idx = sb.lastIndexOf("?");
                if (idx < 0) {
                    break;
                }
                
                String s = sb.charAt(idx - 1) == 'T' ? sb.substring(idx + 1, idx + 2) : sb.substring(idx + 3, idx + 4);
                sb.replace(idx - 1, idx + 4, s);
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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