42.接雨水 |76.最小覆盖子串 | 85.最大矩形 | 84.柱状图中最大矩形面积 |

class Solution {
    public int trap(int[] height) {
        int res = 0;
        Stack stack = new Stack<>();
        
        for(int i=0;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 smap = new HashMap<>();
        Map 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

单调栈应用找第一个比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 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
class Solution {
    public int largestRectangleArea(int[] heights) {
        Stackst = 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;
    }
}

你可能感兴趣的:(算法,数据结构)