😬394 decode string

https://leetcode.com/problems/decode-string/description/

自己做出来就很有成就感,注意递归的使用,还有j是在找与i所在括号匹配的右括号,而不是任意右括号,所以会有leftCnt,同时j是停在右括号的右边,还有注意while要有等号因为end是inclusive的

class Solution {
    public String decodeString(String s) {
        char[] array = s.toCharArray();
        return decode(array, 0, array.length - 1);
    }
    private String decode(char[] array, int start, int end) {
        if (start > end) return "";
        int cnt = 0;
        int i = start;
        StringBuilder sb = new StringBuilder();
        while (i <= end) {
            char ch = array[i];
            if (ch >= '0' && ch <= '9') {
                cnt = cnt * 10 + (ch - '0');
                i++;
            } else if (ch == '[') {
                int j = i + 1;
                int leftCnt = 1;
                while (leftCnt > 0) {
                    if (array[j] == '[') {
                        leftCnt++;
                    } else if (array[j] == ']') {
                        leftCnt--;
                    }
                    j++;
                }
                String segment = decode(array, i + 1, j - 2);
                // System.out.println(i);
                for (int k = 0; k < cnt; k++) {
                    sb.append(segment);
                }
                cnt = 0;
                i = j;
            } else {
                sb.append(ch);
                i++;
            }
        }
        return sb.toString();
    }
}

Last updated