leetcode 85. 最大矩形

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Viscu/article/details/82287309

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
[“1”,”0”,”1”,”0”,”0”],
[“1”,”0”,”1”,”1”,”1”],
[“1”,”1”,”1”,”1”,”1”],
[“1”,”0”,”0”,”1”,”0”]
]
输出: 6

对矩形每行利用单调栈(递增).

  第一行:     ["1","0","1","0","0"],

  第二行:     ["1","0","1","0","0"],
             ["1","0","1","1","1"],

以此类推。

其实就是这道题的升级版: 传送门

class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix.length==0||matrix[0].length==0){
            return 0;
        }
        int[] h=new int[matrix[0].length];
        int n=matrix.length;
        int m=matrix[0].length;
        int ans=0;
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                h[j]=matrix[i][j]=='0'?0:h[j]+1;
            }
            ans=Math.max(ans,solve(h));
        }
        return ans;
    }

    static class pos{
        int l,r,index,h;
    }

    public int solve(int[] h){
        Stack<pos> st=new Stack<pos>();
        pos[] t=new pos[h.length];
        for(int i=0;i<h.length;++i){
            t[i]=new pos();
            t[i].l=i;
            t[i].index=i;
            t[i].h=h[i];
        }
        for(int i=0;i<h.length;++i){
            while (!st.isEmpty()&&st.peek().h>t[i].h){
                t[st.peek().index].r=i;
                t[i].l=st.peek().l;
                st.pop();
            }
            st.push(t[i]);
        }
        while (!st.isEmpty()){
            t[st.pop().index].r=h.length;
        }
        int ans=0;
        for(int i=0;i<h.length;++i){
            ans=Math.max(ans,(t[i].r-t[i].l)*t[i].h);
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/Viscu/article/details/82287309