leetcode 85.Maximal Rectangle

与之前求直方图的最大面积类似,对于行从上到下把所有的高度累计求和出来然后根据这些值来求解最大的面积的。

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int res=0;
        if(matrix.size()==0) return 0;
        int m=matrix.size(), n=matrix[0].size();
        vector<int> height(n,0);
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                height[j]=(matrix[i][j]=='0')?0:height[j]+1;
            }
            res=max(res,helper(height));
        }
        return res;
    }
    
    int helper(vector<int>& height){
        int res=0;
        height.push_back(0);
        stack<int> st;
        for(int i=0;i<height.size();i++){
            if(st.empty()||height[i]>height[st.top()]){
                st.push(i);
            }else{
                int temp=st.top(); st.pop();
                res=max(res, height[temp]*(st.empty()?i:i-st.top()-1));
                i--;
            }
        }
        return res;
    }
};

 

posted on 2018-09-12 16:56  昔风不止,唯有努力生存  阅读(143)  评论(0编辑  收藏  举报

导航