Leetcode 85. 最大矩形
阿新 • • 發佈:2019-01-31
藉助上一題的答案,
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int Len = heights.size();
vector<int> sta, L(Len, 0), R(Len, 0);
for (int i = 0; i < Len; ++i) {
while (!sta.empty() && heights[sta.back()] > heights[i]) {
int x = sta.back(); sta.pop_back();
R[x] = i - 1;
}
sta.push_back(i);
}
while (!sta.empty()) {
int x = sta.back(); sta.pop_back();
R[x] = Len - 1;
}
for (int i = Len - 1; i >= 0; --i) {
while (!sta.empty() && heights[sta.back()] > heights[i]) {
int x = sta.back(); sta.pop_back();
L[x] = i + 1;
}
sta.push_back(i);
}
while (!sta.empty()) {
int x = sta.back(); sta.pop_back();
L[x] = 0;
}
int ans = 0;
for (int i = 0; i < Len; ++i)
ans = max(ans, (R[i] - L[i] + 1 )*heights[i]);
return ans;
}
int maximalRectangle(vector<vector<char>>& matrix) {
int n = matrix.size(), m = n == 0 ? 0 : matrix[0].size(), ans = 0;
vector<vector<int>> up(n, vector<int>(m, 0)), left(n, vector<int>(m, 0));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (matrix[i][j] == '1') {
if (i == 0) up[i][j] = 1;
else up[i][j] = up[i - 1][j] + 1;
if (j == 0) left[i][j] = 1;
else left[i][j] = left[i][j - 1] + 1;
}
vector<int> heights(m, 0);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j)
heights[j] = up[i][j];
ans = max(ans, largestRectangleArea(heights));
}
heights.assign(n, 0);
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i)
heights[i] = left[i][j];
ans = max(ans, largestRectangleArea(heights));
}
return ans;
}
};