美文网首页
394. 字符串解码

394. 字符串解码

作者: 编程小王子AAA | 来源:发表于2020-08-09 09:44 被阅读0次

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

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

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

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

示例 1:

输入:s = "3[a]2[bc]"
输出:"aaabcbc"
示例 2:

输入:s = "3[a2[c]]"
输出:"accaccacc"
示例 3:

输入:s = "2[abc]3[cd]ef"
输出:"abcabccdcdcdef"
示例 4:

输入:s = "abc3[cd]xyz"
输出:"abccdcdcdxyz"


class Solution {
    public String decodeString(String s) {
        Stack<Integer> numStack = new Stack();
        Stack<String> strStack = new Stack();
        StringBuilder sb = new StringBuilder();
        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                num = num * 10 + c - '0';
            } else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                sb.append(c);
            } else if (c == '[') {
                if (num > 0) numStack.push(num);
                strStack.push(sb.toString());
                sb = new StringBuilder();
                num = 0;
            } else {
                //c==']'
                StringBuilder preSB = new StringBuilder(strStack.pop());
                int times = numStack.pop();
                for (int j = 0; j < times; j++) {
                    preSB.append(sb);
                }
                sb = preSB;
            }
        }
        return sb.toString();
    }
}

相关文章

  • 打卡-字符串解码

    394. 字符串解码

  • 394. 字符串解码

    394.字符串解码给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string...

  • 394. 字符串解码

    394. 字符串解码 给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_stri...

  • LeetCode 394. 字符串解码 | Python

    394. 字符串解码 题目来源:力扣(LeetCode)https://leetcode-cn.com/probl...

  • 394.字符串解码

    ​394.字符串解码 题目分析 对这个题目的需求进行分析(需求分析来自Leetcode用户名为凛冬[1])我只是稍...

  • 394. 字符串解码

    题目描述 给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示...

  • 394.字符串解码

    执行用时 :1 ms, 在所有Java提交中击败了90.09%的用户 内存消耗 :37.4 MB, 在所有Java...

  • 394. 字符串解码

    给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号...

  • 394. 字符串解码

    题目链接:https://leetcode-cn.com/problems/decode-string/ 解题思路...

  • 394. 字符串解码

    解法

网友评论

      本文标题:394. 字符串解码

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