[leetcode]Maximal Rectangle

按Largest Rectangle in Histogram的方法做

每行求一次max

每次更新的height就是当前列到0行那列0的个数(包含当前行

然后用height来求largest rectangle

 

class Solution {
public:
    void getLeft(const vector<int>& h , vector<int>& l) {
        int size = h.size();
        for(int i = 1 ; i < size ; ++i) {
            while(l[i] > 0 && h[i] <= h[l[i]-1]) l[i] = l[l[i]-1];
        }
    }
    void getRight(const vector<int>& h, vector<int>& r) {
        int size = h.size();
        for(int i = size - 2 ; i >=0 ; --i) {
            while(r[i] < size - 1 && h[i] <= h[r[i] + 1]) r[i] = r[r[i] + 1];
        }
    }
    int maxRec(const vector<int>& h) {
        int size = h.size();
        int result = 0;
        vector<int> l(size , 0);
        vector<int> r(size , 0);
        for(int i = 0 ; i < size ; ++i) {
            l[i] = i;
            r[i] = i;
        }
        getLeft(h , l);
        getRight(h , r);
        
        for(int i = 0 ; i < size ; ++i) {
            result = max(result , (r[i]-l[i]+1)*h[i]);
        }
        return result;
    }
    int maximalRectangle(vector<vector<char> > &matrix) {
        //n * m matrix
        int n = matrix.size();
        if(n == 0) return 0;
        int m = matrix.front().size();
        vector<int> h(m , 0);
        for(int i = 0 ; i < m ; ++i) h[i] = matrix[0][i] - '0';
        int result = maxRec(h);
        for(int i = 1 ; i < n ; ++i) {
            for(int j = 0 ; j < m ; ++j) {
                if(matrix[i][j] == '0' ) {
                    h[j] = 0;
                } else {
                    ++h[j];
                }
            }
            int tmpMax = maxRec(h);
            result = max(result , tmpMax);
        }
        return result;
    }
};

 

 

你可能感兴趣的:(LeetCode)