思路:借鉴网上的讨论,此题和前面一个直方图最大面积类似,只是现在需要把矩阵的每一行转化成一个直方图,然后计算每一行的最大面积即可,其余思路见代码注释
code:
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if(matrix.empty())
return 0;
int maxArea = 0;
int nRows = matrix.size(),nCols = matrix[0].size();
vector<int> rows(nCols,0);
for(int i = 0;i < nRows;i++){
for(int j =0;j <nCols;j++){//当前行的直方图值
if(matrix[i][j] == '1')
rows[j]++;
else
rows[j] = 0;
}
int curMax = singleRowMax(rows,nCols);
maxArea = max(maxArea,curMax);
}
return maxArea;
}
int singleRowMax(vector<int> &row,int n){//计算一行的直方图最大面积
int i = 0;
stack<int> s;
int maxArea = 0;
while(i < n){
if(s.empty() || row[i] >= row[s.top()]){//栈中存储递增的序列,而且到当前位置,最小的值一定在栈底
s.push(i);
++i;
}
else{//如果当前位置要小于栈顶元素,则以栈顶元素为高,弹栈,长度为新栈顶和当前元素之间的距离(因为旧栈顶和新栈顶之间的元素一定比新旧栈顶的元素要大,或者新旧栈顶连续)
int curIndex = s.top();
s.pop();
int curValue = row[curIndex] * (s.empty() ? i : i - s.top() - 1);
maxArea = max(maxArea,curValue);
}
}
while(!s.empty()){
int curIndex = s.top();
s.pop();
int curValue = row[curIndex] * (s.empty() ? n : n - s.top() - 1);
maxArea = max(maxArea,curValue);
}
return maxArea;
}
};