
解题思路:
- 数字栈: 存储重复次数 num。
- 字符串栈: 存储当前已解码的字符串 current。
- 遍历字符串:
- 数字:累积构建当前重复次数。
- 左括号 [:将当前数字和字符串压栈,重置临时变量。
- 右括号 ]:弹出栈顶的重复次数和之前的字符串,将当前字符串重复 repeat 次后拼接。
- 字母:直接追加到当前字符串。
- 返回结果: return String.valueOf(current);
Java代码:
class Solution {public String decodeString(String s) {Deque<Integer> numStack = new LinkedList<>();Deque<StringBuilder> strStack = new LinkedList<>();StringBuilder current = new StringBuilder();int num = 0;for (char c : s.toCharArray()) {if (Character.isDigit(c)) {num = num * 10 + (c - '0');} else if (c == '[') {numStack.push(num);strStack.push(current);current = new StringBuilder();num = 0;} else if (c == ']') {int repeat = numStack.pop();StringBuilder temp = current;current = strStack.pop();current.append(String.valueOf(temp).repeat(repeat));} else {current.append(c);}}return String.valueOf(current);}
}
复杂度分析:
- 时间复杂度: O(N,其中 N 是解码后字符串的总长度。每个字符最多被处理一次,重复拼接的复杂度由解码后的字符串长度决定。
- 空间复杂度: O(M),其中 M 是输入字符串的最大嵌套深度。栈的空间消耗与嵌套层数相关。

解题思路:
- 初始化: 创建结果数组 answer(初始化为全0)和栈 stack(存储索引)。
- 遍历温度数组: 对于当前温度 temperatures[i],若栈不为空且栈顶索引对应的温度小于当前温度,弹出栈顶索引 index,计算天数差 i - index,存入 answer[index],将当前索引 i 压入栈。
- 返回结果: 遍历结束后,返回 answer 数组。
Java代码:
class Solution {public int[] dailyTemperatures(int[] temperatures) {int[] answer = new int[temperatures.length];Deque<Integer> stack = new LinkedList<>();for (int i = 0; i < temperatures.length; i++) {while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {int index = stack.pop();answer[index] = i - index;}stack.push(i);}return answer;}
}
复杂度分析:
- 时间复杂度: O(n),其中 n 是数组长度。
- 空间复杂度: O(n)。最坏情况下栈需要存储所有索引。