有效的括號(020)
跳過
最小棧(155)
class MinStack {
private final Deque<int[]> stack = new ArrayDeque<>();
public MinStack() {
stack.addLast(new int[]{0, Integer.MAX_VALUE});
}
public void push(int val) {
stack.addLast(new int[]{val, Math.min(stack.peekLast()[1], val)});
}
public void pop() {
stack.removeLast();
}
public int top() {
return stack.peekLast()[0];
}
public int getMin() {
return stack.peekLast()[1];
}
}
- 分析
使用雙端隊列作棧
利用動態規劃, 每個棧元素維護自身val和min_val
字符串解碼(394)
class Solution {
public String decodeString(String s) {
int idx = 0;
StringBuilder builder = new StringBuilder();
while (idx < s.length()){
// 是字母
if (s.charAt(idx) >= 'a'){
builder.append(s.charAt(idx));
idx++;
continue;
}
idx = appendDupString(idx, s, builder);
//是數字
}
return builder.toString();
}
private int appendDupString(int idx, String s , StringBuilder builder){
int prefix_count = 0;
while(s.charAt(idx) != '['){
prefix_count = prefix_count * 10 + s.charAt(idx) - '0';
idx++;
}
int rig_idx = idx+1;
int nest = 1;
while (nest != 0){
if (s.charAt(rig_idx) == '[') nest++;
else if (s.charAt(rig_idx) == ']') nest--;
rig_idx++;
}
String subString = decodeString(s.substring(idx+1, rig_idx-1));
for (int i = 0; i < prefix_count; i++){
builder.append(subString);
}
return rig_idx;
}
}
- 分析
遞歸調用
每日溫度(739)
棧解法
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] res = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = n-1; i >= 0; i--){
int t = temperatures[i];
while(!stack.isEmpty() && t >=temperatures[stack.peek()]){
stack.pop();
}
if (!stack.isEmpty()){
res[i] = stack.peek() - i;
}
stack.push(i);
}
return res;
}
}
跳表解法
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] res = new int[n];
for (int i = n-2; i >= 0; i--){
for (int j = i+1; j < n; j += res[j]){
if (temperatures[j] > temperatures[i]){
res[i] = j - i;
break;
}
else if (res[j] == 0){
res[i] = 0;
break;
}
}
}
return res;
}
}
- 分析
棧解法
棧用于維護<最近><關聯>數據
維護棧的單調性就是在維護棧組中的數據的<關聯>性, 棧自身的性質可以用于保持<最近>特性
跳表解法
可能也許這是貪心
柱狀圖中最大矩形(084)
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(-1);
int res = 0;
for (int rig = 0; rig <= n; i++){
int h = rig < n ? heights[rig] : -1;
while(stack.size() > 1 && h <= heights[stack.peek()]){
int height = heights[stack.pop()];
int lef = stack.peek();
res = Math.max(res, height * (rig - lef - 1));
}
stack.push(rig);
}
return
}
}
- 分析
維護棧的單調性, 非單調時彈出數據作max比較
浙公網安備 33010602011771號