Java 3ms Solution using Recursion


  • 0
    F
    public class Solution {
        private class Index {
            public int val = 0;
        }
    
        public String decodeString(String s) {
            return helper(s, new Index());
        }
    
        private String helper(String s, Index idx) {
            StringBuilder sbStr = new StringBuilder();
    
            while(idx.val<s.length() && s.charAt(idx.val)!=']') {
                String freqStr;
                int end;
    
                for(end = idx.val; end<s.length() && s.charAt(end)>='a' && s.charAt(end)<='z'; end++);
                sbStr.append(s.substring(idx.val, end));
                idx.val = end;
    
                for(; end<s.length() && s.charAt(end)>='0' && s.charAt(end)<='9'; end++);
                freqStr = s.substring(idx.val, end);
                idx.val = end;
    
                if(freqStr.length() > 0) {
                    idx.val++;
    
                    int freq = Integer.parseInt(freqStr);
                    String repeated = helper(s, idx);
                    while(freq-- > 0) {
                        sbStr.append(repeated);
                    }
                }
            }
    
            idx.val++;   //To skip ']'        
            return sbStr.toString();
        }
    }
    

Log in to reply
 

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