leetcode-85 最大矩形(单调栈)

题目链接
和84类似

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.size()==0)
            return 0;
        int Width = matrix[0].size();
        int Height = matrix.size();
        vector<vector<int> > heights;
        heights.resize(Height);
        for(int i=0;i<Height;i++)
            heights[i].resize(Width);
        for(int i=0;i<Width;i++)
        {
            if(matrix[0][i]=='1')
                heights[0][i] = 1;
        }
        for(int i=1;i<Height;i++)
        {
            for(int j=0;j<Width;j++)
            {
                if(matrix[i][j]=='1')
                {
                    heights[i][j] = heights[i-1][j] + 1;
                }
                else{
                    heights[i][j] = 0;
                }
            }
        }
        int maxArea = 0;
        for(int i=0;i<Height;i++)
        {
            stack<int> s;
            s.push(-1);
            for(int j=0;j<Width;j++)
            {
                while(s.top()!=-1&&heights[i][j]<heights[i][s.top()])
                {
                    int top = s.top();
                    s.pop();
                    maxArea = max(maxArea, heights[i][top]*(j-s.top()-1));
                }
                s.push(j);
            }
            while(s.top()!=-1)
            {
                int top = s.top();
                s.pop();
                maxArea = max(maxArea, heights[i][top]*(Width-s.top()-1));
            }
        }
        return maxArea;
    }
};
原创文章 39 获赞 5 访问量 4921

猜你喜欢

转载自blog.csdn.net/q1072118803/article/details/105296816