Java Concise Solution --- Recursive


  • 0

    My First Post, welcome to discuss :)

        public String decodeString(String s) {
            return decode("1[" + s + "]", 0);
        }
        // PRE: s.charAt(start) is letter or number
        private String decode(String s, int start) {
            if (start >= s.length()) return "";
            if (Character.isLetter(s.charAt(start))) {
                return s.charAt(start) + decode(s, start + 1);
            }
            int idx = start;
            while (Character.isDigit(s.charAt(idx))) {
                idx++;
            } // idx = [
            int times = Integer.parseInt(s.substring(start, idx++));
            int subStart = idx;
            int count = 1;
            while (count > 0) {
                if (s.charAt(idx) == ']') {
                    count--;
                } else if (s.charAt(idx) == '[') {
                    count++;
                }
                idx++;
            }
            String sub = decode(s.substring(subStart, idx-1), 0);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < times; i++) {
                sb.append(sub);
            }
            return sb.toString() + decode(s, idx);
        }
    

Log in to reply
 

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