class Solution {
public int trap(int[] height) {
int res = 0;
Stack<Integer> stack = new Stack<>();
for(int i=0;i<height.length;i++){
while(!stack.isEmpty() && height[i] > height[stack.peek()]){
int mid = stack.pop();
if(stack.isEmpty()) break;
res += (Math.min(height[i],height[stack.peek()])-height[mid]) * (i-stack.peek()-1);
}
stack.push(i);
}
return res;
}
}
class Solution {
public String minWindow(String s, String t) {
Map<Character,Integer> smap = new HashMap<>();
Map<Character,Integer> tmap = new HashMap<>();
int left=0, right=0,start =0;
int vaild = 0;
int minLin = Integer.MAX_VALUE;
for(char c: t.toCharArray()){
tmap.put(c,tmap.getOrDefault(c,0)+1);
}
while(right<s.length()){
char schar = s.charAt(right);
right++;
if(tmap.containsKey(schar)){
smap.put(schar,smap.getOrDefault(schar,0)+1);
if(tmap.get(schar).equals(smap.get(schar))){
vaild++;
}
}
while(vaild == tmap.size()){
if(right - left < minLin){
start = left;
minLin = right-left;
}
char leftchar = s.charAt(left);
left++;
if(tmap.containsKey(leftchar)){
if(tmap.get(leftchar).equals(smap.get(leftchar))){
vaild--;
}
smap.put(leftchar,smap.get(leftchar)-1);
}
}
}
return minLin == Integer.MAX_VALUE ? "" : s.substring(start,minLin+start);
}
}
单调栈应用找第一个比i大或者小的情况;
如果找第一个比他大的,站内单调递增;//接雨水
如果找第一个比他小的,站内单调递减;//最大矩形面积
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length == 0){
return 0 ;
}
//每一行作为底部,输出以这行为底的高度列表
int rows = matrix.length;//列
int cols = matrix[0].length;
int res =0;
int[] high = new int[cols];
for(int i = 0;i<rows;i++){
for(int j = 0;j<cols;j++){
if(matrix[i][j] =='1'){
high[j]++;
}else{
high[j] =0;
}
}
res = Math.max(res,rowRes(high));
}
return res;
}
private int rowRes(int[] high){
Stack<Integer> st = new Stack<>();
st.push(0);
int res=0;
int n = high.length;
for(int i=0;i<=n;i++){
int h=(i==n) ? 0:high[i];
while(!st.isEmpty() && h<high[st.peek()] ){
int j = st.pop();
int width = st.isEmpty()?i:(i-st.peek()-1);
res = Math.max(res, width* high[j]);
}
st.push(i);
}
return res;
}
}
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer>st = new Stack<>();
int res=0;
for(int i=0;i<=heights.length;i++){
//哨兵,保证栈内元素全部处理
int curhigh = (i==heights.length) ? 0 : heights[i];
while(!st.isEmpty() && curhigh < heights[st.peek()] ){
int high = heights[st.pop()] ;
int width = st.isEmpty()? i : i-st.peek()-1;
res = Math.max(res,width *high);
}
st.push(i);
}
return res;
}
}