[LeetCode Hot 100] LeetCode394. 字符串解码

发布时间 2023-12-24 17:10:35作者: Ac_c0mpany丶

题目描述

思路


思路:

  • 碰到数字:压入数字栈,注意多位数的情况
  • 碰到字母:直接拼接到res
  • 遇到[:将num和res分别压入栈
  • 遇到]:开始处理栈顶元素

方法一:

class Solution {
    public String decodeString(String s) {
        int num = 0;
        StringBuilder res = new StringBuilder();
        Deque<String> DigStack = new ArrayDeque<>();
        Deque<Integer> NumStack = new ArrayDeque<>();

        for (char c : s.toCharArray()) {
            if (c >= '0' && c <= '9') {
                num = num * 10 + (c - '0');
            } else if (c == '[') {
                NumStack.push(num);
                DigStack.push(res.toString());
                res.delete(0, res.length());
                num = 0;
            } else if (c == ']') {
                String item = res.toString();
                int times = NumStack.pop();
                for (int i = 0; i < times - 1; i ++) {
                    res.append(item);
                }
                res.insert(0, DigStack.pop());
            } else{
                res.append(c);
            }
        }
        return res.toString();
    }
}