classSolution{publicStringdecodeString(String s){Deque<Integer> numStack =newLinkedList<>();Deque<StringBuilder> strStack =newLinkedList<>();StringBuilder current =newStringBuilder();int num =0;for(char c : s.toCharArray()){if(Character.isDigit(c)){
num = num *10+(c -'0');}elseif(c =='['){
numStack.push(num);
strStack.push(current);
current =newStringBuilder();
num =0;}elseif(c ==']'){int repeat = numStack.pop();StringBuilder temp = current;
current = strStack.pop();
current.append(String.valueOf(temp).repeat(repeat));}else{
current.append(c);}}returnString.valueOf(current);}}
复杂度分析:
时间复杂度: O(N,其中 N 是解码后字符串的总长度。每个字符最多被处理一次,重复拼接的复杂度由解码后的字符串长度决定。
空间复杂度: O(M),其中 M 是输入字符串的最大嵌套深度。栈的空间消耗与嵌套层数相关。
解题思路:
初始化: 创建结果数组 answer(初始化为全0)和栈 stack(存储索引)。
遍历温度数组: 对于当前温度 temperatures[i],若栈不为空且栈顶索引对应的温度小于当前温度,弹出栈顶索引 index,计算天数差 i - index,存入 answer[index],将当前索引 i 压入栈。
返回结果: 遍历结束后,返回 answer 数组。
Java代码:
classSolution{publicint[]dailyTemperatures(int[] temperatures){int[] answer =newint[temperatures.length];Deque<Integer> stack =newLinkedList<>();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;}}