美文网首页
394. Decode String

394. Decode String

作者: FlynnLWang | 来源:发表于2016-10-06 10:13 被阅读0次

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

相关文章

网友评论

      本文标题:394. Decode String

      本文链接:https://www.haomeiwen.com/subject/qfseyttx.html