JAVA, one pass, recursive solution.


  • 0
    I
    /*
     * Recursive. helper(s) consumes one layer of "[ ]".
     */
        int idx;
        public String decodeString(String s) {
            idx = 0;
            return helper(s);
        }
        String helper(String s) {
            StringBuilder ans = new StringBuilder();
            for (int k = 0; idx < s.length(); ++idx) {
                char ch = s.charAt(idx);
                if (ch == '[') {
                    ++idx;
                    String str = helper(s);
                    while (k > 0) {
                        ans.append(str);
                        --k;
                    }
                } else if (ch == ']') {
                    break;
                } else if (Character.isDigit(ch)) {
                    k = k * 10 + ch - '0';
                } else ans.append(ch);
            }
            return ans.toString();
        }
    

Log in to reply
 

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