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"
提示:
1 <= s.length <= 30
s
由小写英文字母、数字和方括号'[]'
组成s
保证是一个 有效 的输入。s
中所有整数的取值范围为[1, 300]
class Solution {
public String decodeString(String s) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
int tempi = i + 1;
while (Character.isDigit(s.charAt(tempi))) {
tempi++;
}
stack.add(s.substring(i, tempi));
i = tempi - 1;
} else if (c == ']') {
String str = "";
while (!stack.isEmpty()) {
String pop = stack.pop();
if ("[".equals(pop)) {
break;
} else {
str = pop + str;
}
}
int num = Integer.valueOf(stack.pop());
StringBuilder newInnerStr = new StringBuilder();
for (int j = 0; j < num; j++) {
newInnerStr.append(str);
}
stack.add(newInnerStr.toString());
} else {
stack.add("" + c);
}
}
String ans = "";
while (!stack.isEmpty()) {
String pop = stack.pop();
ans = pop + ans;
}
return ans;
}
}
739. 每日温度
给定一个整数数组 temperatures
,表示每天的温度,返回一个数组 answer
,其中 answer[i]
是指对于第 i
天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0
来代替。
示例 1:
temperatures
示例 2:
输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]
示例 3:
输入: temperatures = [30,60,90]
输出: [1,1,0]
提示:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
// 维护单调栈
Deque<int[]> q = new ArrayDeque<>();
int n = temperatures.length;
int[] res = new int[n];
for (int i = 0; i < n; i++) {
int t = temperatures[i];
// 维护单调栈,过程中推出的栈顶元素更新到答案中
while (!q.isEmpty() && t > q.peekLast()[0]) {
int[] arr = q.pollLast();
res[arr[1]] = i - arr[1];
}
q.addLast(new int[] { t, i });
}
return res;
}
}