Loading

力扣 - 394. 字符串解码

题目

394. 字符串解码

思路

  • 创建两个栈进行解题,一个用来存放数字,另一个用来临时存放子字符串
  • 由于可能会在[]中还包含其他的[],所以我们只要遇到[就先将其前面的字符串暂时入栈,稍后再进行计算
  • 如果遇到] ,则将存放数字的栈和存放子字符串的栈分别出栈一个,然后进行字符串的拼接,然后再将该字符串作为答案的一部分进行下一轮迭代计算

代码

class Solution {
    public String decodeString(String s) {
        Deque<Integer> times = new LinkedList<Integer>();
        Deque<String> stringStack = new LinkedList<String>();
        StringBuilder res = new StringBuilder();
        int count = 0;

        for (Character c : s.toCharArray()) {
            // 如果为数字,则记录数字,数字有可能有十位或者百位
            if (isNum(c)) {
                count = count * 10 + Integer.parseInt("" + c);
            } else if (c == '[') { // 如果为左中括号,则将数字和当前的res进栈
                times.push(count);
                stringStack.push(res.toString());
                // 注意还要将res置空,因为要开始下一轮的字符串统计,上一轮的字符串已经先暂存到栈中去了
                res = new StringBuilder();
                // 次数也要置为0
                count = 0;
            } else if (c == ']') { // 如果为右中括号,则要开始计算本次统计的res,添加到上一个字符串的末尾
                // 获取次数
                count = times.pop();
                StringBuilder curString = new StringBuilder(stringStack.pop());
                for (int i = 0; i < count; i++) {
                    curString.append(res);
                }
                // 将拼接好后的字符串作为结果进行下一轮迭代
                res = curString;
                count = 0;
            } else {
                // 如果都是字母的话仅进行平解字符串即可
                res.append(c);
            }
        }

        return res.toString();
    }

    public boolean isNum(char c) {
        // 判断字符是否为数字
        if (c <= '9' && c >= '0') {
            return true;
        }
        return false;
    }
}

复杂度分析

  • 时间复杂度:\(O(N)\),N为字符串的长度
  • 空间复杂度:\(O(N)\),N为字符串的长度
posted @ 2020-11-04 20:07  linzeliang  阅读(198)  评论(0)    收藏  举报