[leetcode刷题系列]Maximal Rectangle

利用上一提的函数就行了- -


const int MAXN = 1e6 + 10;

int n;
int pleft[MAXN], pright[MAXN];
stack<int> stk;


class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        n = height.size();
        //left
        for(int i = n - 1; i >= 0; -- i){
            while(!stk.empty()){
                int now = stk.top();
                if(height[i] < height[now]){
                    pleft[now] = i;
                    stk.pop();
                }else break;
            }
            stk.push(i);
        }
        while(!stk.empty()){
            pleft[stk.top()] = -1;
            stk.pop();
        }
        // right
        for(int i = 0; i < n; ++ i){
            while(!stk.empty())
                if(height[i] < height[stk.top()]){
                    pright[stk.top()] = i;
                    stk.pop();
                }else break;
            stk.push(i);
        }
        while(!stk.empty()){
            pright[stk.top()] = n;
            stk.pop();
        }
        int ans = 0;
        for(int i = 0; i < n; ++ i)
            ans = max(ans, height[i] *(pright[i] - pleft[i] - 1));
        return ans;
    }
    int maximalRectangle(vector<vector<char> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(matrix.size() <= 0)
            return 0;
        vector<int> now(matrix[0].size(), 0);
        int ans = 0;
        for(int i =  0; i < matrix.size(); ++ i){
            for(int j = 0; j < matrix[i].size(); ++ j)
                if(matrix[i][j] == '1')
                    now[j] ++ ;
                else
                    now[j] = 0;
            ans = max(ans, largestRectangleArea(now));
        }
        return ans;
    }
};


你可能感兴趣的:([leetcode刷题系列]Maximal Rectangle)