Share my straightforward java recursive solution


  • 0
    S
    public String decodeString(String s) {
            int[] i = new int[1];
            String result = decodeString_recursive_helper(s, i);
            return result;
        }
        
            private String decodeString_recursive_helper(String s, int[] i) {
            StringBuilder sb = new StringBuilder();
            int number = 0;
            while(i[0] < s.length() && s.charAt(i[0]) != ']') {
                if(Character.isDigit(s.charAt(i[0]))) {
                    number = number * 10 + s.charAt(i[0]) - '0';
    
                }else if(s.charAt(i[0]) == '[') {
                    ++i[0]; // skip '['
                    String substring = decodeString_recursive_helper(s, i);
                    while (number > 0) {
                        sb.append(substring);
                        number--;
                    }
                } else {
                    sb.append(s.charAt(i[0]));
                }
                ++i[0];
    
            }
            return sb.toString();
        }
    

Log in to reply
 

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