艾恩凝
个人博客 https://aeneag.xyz/
公众号 技术乱舞
每日一练,保持手感
2021/10/17
题目
https://leetcode-cn.com/problems/maximal-rectangle/
题目分析
本题基于84题解决,这就很简单了,由上到下,首先第一行,其次前两行每列相加,如果有0 就全部为0
题解
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0 ,len = heights.size();
stack<int> my_stack;
vector<int> new_heights(len+2,0);
for(int i = 1 ; i < len + 1 ; ++i)new_heights[i] = heights[i-1];
for(int i = 0 ; i < len+2 ; ++i){
while(!my_stack.empty() && new_heights[i] < new_heights[my_stack.top()]){
int cur = my_stack.top();
my_stack.pop();
int cur_height = new_heights[cur];
int left = my_stack.top();
int right = i;
int width = right - left - 1;
res = max(res,cur_height*width);
}
my_stack.push(i);
}
return res;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.size() == 0)return 0;
int row = matrix.size(),col = matrix[0].size();
vector<int> tmp(col,0);
//for(int i = 0 ; i < col ; ++i)tmp[i] = atoi(matrix[0][i]);
//此处char 转int 不知道为什么这个函数说没有,换了写法
int res = largestRectangleArea(tmp);
for(int i = 0 ; i < row ; ++i){
for(int j = 0 ; j < col ; ++j){
//tmp[j] += atoi(matrix[i][j]);
if(matrix[i][j] == '1'){
++tmp[j];
}else{
tmp[j] = 0;
}
}
res = max(res,largestRectangleArea(tmp));
}
return res;
}
};
欢迎关注 #公众号:技术乱舞 一起交流
灵魂碰撞