题目连接:Leetcode 085 Maximal Rectangle
解题思路:做过 Leetcode 084,这题就很简单了,将没一行都看作是一个数组,向上最大连续的1个数作为高。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
int* l = new int[n];
int* r = new int[n];
int* t = new int[n+1];
int* p = new int[n+1];
t[0] = -1, p[0] = -1;
int c = 1;
for (int i = 0; i < n; i++) {
while (c > 0 && t[c-1] >= heights[i]) c--;
l[i] = p[c-1] + 1;
t[c] = heights[i];
p[c++] = i;
}
p[0] = n, c = 1;
for (int i = n-1; i >= 0; i--) {
while (c > 0 && t[c-1] >= heights[i]) c--;
r[i] = p[c-1] - 1;
t[c] = heights[i];
p[c++] = i;
}
int ans = 0;
for (int i = 0; i < n; i++)
ans = max(ans, (r[i] - l[i] + 1) * heights[i]);
delete[] l;
delete[] r;
delete[] t;
delete[] p;
return ans;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) return 0;
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> gph;
int ans = 0;
for (int i = 0; i < m; i++) {
vector<int> g;
for (int j = 0; j < n; j++) {
int k = (i == 0 ? 0 : gph[i-1][j]);
int c = (matrix[i][j] == '1' ? k + 1 : 0);
g.push_back(c);
}
ans = max(ans, largestRectangleArea(g));
gph.push_back(g);
}
return ans;
}
};