394-字符串解码

394-字符串解码

给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

示例:

s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    public String decodeString(String s) {
        char[] chs = s.toCharArray();

        Stack<String> strs = new Stack<>();
        Stack<Integer> nums = new Stack<>();
        StringBuilder tmp = new StringBuilder();

        StringBuilder res = new StringBuilder();
        for (int i = 0; i < chs.length; i++) {
            char c = chs[i];
            if (Character.isDigit(c)) {
                int k = c - '0';
                i++;
                while (Character.isDigit(chs[i])) {
                    k = k * 10 + chs[i++] - '0';
                }
                nums.push(k);
                if(tmp.length() != 0) {
                    strs.push(tmp.toString());
                    tmp = new StringBuilder();
                }
            } else if (c == ']') {
                String ss = "";
                if(nums.size() == strs.size()) {
                    ss = strs.pop();
                }

                int k = nums.pop();
                StringBuilder t = new StringBuilder();
                while (k > 0) {
                    t.append(ss).append(tmp);
                    k--;
                }
                tmp = t;
            } else if (c != '['){
                tmp.append(c);
            }

            if(nums.isEmpty()) {
                res.append(tmp);
                tmp = new StringBuilder();
            }
        }
        return res.toString();
    }
    public String decodeString(String s) {
        char[] chs = s.toCharArray();

        Stack<String> strs = new Stack<>();
        Stack<Integer> nums = new Stack<>();
        StringBuilder tmp = new StringBuilder();
        int k = 0;
        for (int i = 0; i < chs.length; i++) {
            char c = chs[i];
            if (Character.isDigit(c)) {
                while (Character.isDigit(chs[i])) {
                    k = k * 10 + chs[i++] - '0';
                }
                i--;
            } else if (c == ']') {
                String ss = strs.pop();
                int pop = nums.pop();
                StringBuilder t = new StringBuilder(ss);
                while (pop > 0) {
                    t.append(tmp);
                    pop--;
                }
                tmp = t;
            } else if (c != '['){
                tmp.append(c);
            } else {
                nums.push(k);
                strs.push(tmp.toString());
                tmp = new StringBuilder();
                k = 0;
            }
        }
        return tmp.toString();
    }

猜你喜欢

转载自www.cnblogs.com/angelica-duhurica/p/12292574.html