问题
https://leetcode.com/problems/maximal-rectangle/
解法1
转换成LeetCode 84 Largest Rectangle in Histogram
枚举每一行, 统计每一列从当前行向上连续1 的个数作为高度, 然后每一行使用84 中的算法求得最大矩形。
矩形为n行*m列 时间复杂度O(n*m), 空间复杂度O(m);
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty() || matrix[0].empty())
return 0;
int ret = 0;
vector<int> heights(matrix[0].size()+1, 0);
heights[matrix[0].size()] = -1;
stack<int> s;
for (int i=0; i<matrix.size(); ++i)
{
for (int j=0; j<heights.size(); ++j)
{
if(j <matrix[i].size())
{
if (matrix[i][j]=='0')
heights[j] = 0;
else
++heights[j];
}
while(s.size() && heights[j] < heights[s.top()])
{
int h = heights[s.top()];
s.pop();
int start = s.empty()? 0:s.top()+1;
ret = max(ret, h*(j - start));
}
s.push(j);
}
s.pop();
}
return ret;
}
};