【題解】LeetCode 85. Maximal Rectangle

【題目敘述】https://leetcode.com/problems/maximal-rectangle/
【解題想法】單調棧

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int n = matrix.size();
        if (n == 0) return 0;
        int m = matrix[0].size();
        if (m == 0) return 0;
        int a[n+1][m+2] = {};
        int ans = 0;
        for (int i = 1; i <= n; i++){
            for (int j = 1; j <= m; j++){
                if (matrix[i-1][j-1] == '0'){
                    a[i][j] = 0;
                    continue;
                }
                a[i][j] = a[i-1][j]+1;
            }
            stack <int> stk;
            stk.push(0);
            a[i][0] = -1;
            a[i][m+1] = -1;
            int l[m+2] = {}, r[m+2] = {};
            for (int j = 1; j <= m+1; j++){
                while(a[i][stk.top()] > a[i][j]){
                    r[stk.top()] = j;
                    stk.pop();
                }
                stk.push(j);
            }
            for (int j = m; j >= 0; j--){
                while(a[i][stk.top()] > a[i][j]){
                    l[stk.top()] = j;
                    stk.pop();
                }
                stk.push(j);
            }
            for (int j = 1; j <= m; j++){
                ans = max(ans, a[i][j]*(r[j]-l[j]-1));
            }
        }
        return ans;
    }
};
分享本文 Share with friends