Java Easy Understand Solution


  • 0
    X

    Very first thing we want to do is to check the left bucket position and right bucket position. We can mock a stack, whenever we find a left bucket we increase 1, and decrease 1 when find a right bucket.
    Then we can use recursion to solve the sub-problems.

    public class Solution {
        public String decodeString(String s) {
            if (s.indexOf('[') == -1) {
                return s;
            } else {
                int stack = 1, pointer = s.indexOf('[') + 1;
                
                while (stack != 0) {
                    if (s.indexOf('[', pointer) == -1 || s.indexOf('[', pointer) > s.indexOf(']', pointer)) {
                        stack --;
                        pointer = s.indexOf(']', pointer) + 1;
                    } else {
                        stack ++;
                        pointer = s.indexOf('[', pointer) + 1;
                    }
                }
                
                int numStartIndex = s.indexOf('[', 0);
                StringBuilder sb = new StringBuilder();
                while (numStartIndex != 0 && s.charAt(numStartIndex - 1) < 'A') {
                    sb.insert(0, s.charAt(numStartIndex - 1));
                    numStartIndex --;
                }
                int count = Integer.valueOf(sb.toString());
                String res = "";
                res += decodeString(s.substring(0, numStartIndex));
                for (int i = 0; i < count; i ++) {
                    res += decodeString(s.substring(s.indexOf('[', 0) + 1, pointer - 1));
                }
                
                res += decodeString(s.substring(pointer));
                return res;
            }
        }
    }
    

Log in to reply
 

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