您的位置:首页 > 其它

LeetCode之Maximal Rectangle

2015-07-21 22:14 330 查看
/*这道题是Largest Rectangle in Histogram的二维版本,因此可以将一维版本的解法
应用到这道题的解法中。*/
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty()) return 0;
vector<int> height(matrix[0].size()+1, 0);
int res(0);
stack<int> s;
for(int i = 0; i < matrix.size(); ++i){
stack<int>().swap(s);
for(int j = 0; j < matrix[0].size() + 1; ++j){
if(j < matrix[0].size()){
if(matrix[i][j] == '1') ++height[j];
else height[j] = 0;
}
if(s.empty() || height[j] > height[s.top()]) s.push(j);//入栈
else{
while(!s.empty() && height[j] <= height[s.top()]){//出栈
int tmp = s.top();
s.pop();
res = max(res, height[tmp] * (s.empty() ? j : j - s.top() - 1));
}
s.push(j);
}
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: