Java recursive solution


  • 0
    S
    public class Solution {
        int ind = 0;
        public String decodeString(String s) {
            if (s == null || s.length() == 0) return "";
            int count = 0;
            StringBuilder sb = new StringBuilder();
            for (; ind < s.length(); ind++) {
                char c = s.charAt(ind);
                if (Character.isDigit(c)) {
                    count = count*10+c-'0';
                } else if (c=='[') {
                    ind++;
                    String sub = decodeString(s);
                    for (int i=0; i<count; i++) {
                        sb.append(sub);
                    }
                    count = 0;
                } else if (c==']') {
                    return sb.toString();
                } else {
                    sb.append(c);
                }
            }
            return sb.toString();
        }
    }
    111

Log in to reply
 

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