394. Decode String

Question description

Screenshot 2016-10-05 20.47.58.png

My code

public class Solution {
    public String decodeString(String s) {
        StringBuilder sb = new StringBuilder(s);
        for (int i = 0; i < sb.length(); i++) {
            char c1 = sb.charAt(i);
            if (c1 == '[') {
                for (int j = i + 1; j < sb.length(); j++) {
                    char c2 = sb.charAt(j);
                    if (c2 == ']') {
                        int begin = 0;
                        for (int k = i - 1; k >= 0; k --) {
                            if (sb.charAt(k) > 57) {
                                begin = k + 1;
                                break;
                            }
                        }
                        int num = Integer.parseInt(sb.substring(begin, i));
                        String sub = sb.substring(i + 1, j);
                        StringBuilder tmp = new StringBuilder();
                        for (int k = 0; k < num; k++) {
                            tmp.append(sub);
                        }
                        sb.replace(begin, j + 1, tmp.toString());
                        i = 0;
                        break;
                    } else if (c2 == '[') {
                        break;
                    }
                }
            }
        }
        return sb.toString();
    }
}

Solution

For brackets that have no inside brackets, directly multiply the content in the bracket by the number before the bracket. Otherwise, look into the bracket and get the bracket without inner brackets.

Test result

Screenshot 2016-10-05 20.47.38.png

推荐阅读更多精彩内容