Java Recursive Solution with Some Comments


  • 0
    public String decodeString(String s) {
        char[] encoded = s.toCharArray();//It is faster to transfer string into char array than calling s.charAt().
        StringBuffer sb = new StringBuffer();
        helper(encoded,sb,0,0);
        return sb.toString();
        
    }
    private int helper(char[] encoded, StringBuffer sb, int start,int lastcount){//return the position of ']'
        int i = start;
        int count = 0;
        StringBuffer curr = new StringBuffer();
        while(i<encoded.length){
            if(encoded[i]>='0'&&encoded[i]<='9'){
                count=count*10+(int)(encoded[i]-'0');//get the integer before '['.
                i++;
            }
            else if(encoded[i]=='['){
                if(count==0) count = 1; //if there is no digits before '[', the default count is 1.
                i = 1+helper(encoded,curr,i+1,count);
                count = 0;// reset count for conditions like '3[ab]4[e]'. if count is not reset here, it will be 34 for 'e'. 
            }
            else if(encoded[i]==']'){
                for(int j = 0;j<lastcount;j++){
                    sb.append(curr);
                }
                return i;
            }
            else{
                curr.append(encoded[i]);
                i++;
            }
        }
        sb.append(curr);
        return i;
    }

Log in to reply
 

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