3ms Clean and Modularized Java Solution


  • 1
    N

    Recursively decode whenever you encounter digits.

    public class Solution {
        
        boolean isDigit(char c) {
            return c >= '0' && c <= '9';
        }
        
        void appendRepeat(StringBuilder sb, String strToAppend, int count) {
            for (int i = 0; i < count; i++)
                sb.append(strToAppend);
            return;
        }
        
        int getOpenIndex(String s, int start) {
            return s.indexOf('[',start);
        }
        
        int getCloseIndex(String s, int start) {
            int openCount = 1;
            int curr = getOpenIndex(s,start) + 1;
            while(openCount != 0) {
                switch(s.charAt(curr++)) {
                    case '[':
                        openCount++;
                        break;
                    case ']':
                        openCount--;
                        break;
                }
            }
            return curr-1;
        }
        
        public String decodeString(String s) {
            StringBuilder result = new StringBuilder();
            int start = 0, end = 0;
            while (end < s.length()) {
                start = end;
                if (isDigit(s.charAt(start))) {
                    int openIndex = getOpenIndex(s,start);
                    int closeIndex = getCloseIndex(s,start);
                    int count = Integer.parseInt(s.substring(start,openIndex));
                    String enclosedString = s.substring(openIndex+1, closeIndex);
                    appendRepeat(result,decodeString(enclosedString),count);
                    end = closeIndex+1;
                } else {
                    int curr = start;
                    while (curr < s.length() && !(isDigit(s.charAt(curr))))
                        curr++;
                    appendRepeat(result,s.substring(start,curr),1);
                    end = curr;
                }
            }
            return result.toString();
        }
    }
    

Log in to reply
 

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