题目
分析
这道题是84题的进阶版,需要自己去画这个柱形图。
for(int i = 0;i < row;i++){
for(int j = 0;j < col;j++){
if(h[i][j]==1){
count[i][j]=count[i-1][j]+1;
}else{
count[i][j]=0;
}
}
}
然后每一行就是一个柱形图,可以使用84题单调栈解法。
具体代码
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length == 0){
return 0;
}
//先遍历出每一列从第0行开始含连续1的个数,作为每列的高度,接下来就是84题的解法了
int[] height = new int [matrix[0].length];
int maxArea = 0;
for(int row = 0;row < matrix.length;row++){
for(int col = 0;col < matrix[0].length;col++){
if(matrix[row][col] == '1'){
height[col]++;
}else{
height[col] = 0;
}
}
maxArea = Math.max(maxArea,maxi(height));
}
return maxArea;
}
public int maxi(int[] height){
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int maxArea = 0;
for(int i = 0;i < height.length;i++){
while(stack.peek()!=-1&&height[stack.peek()]>height[i]){
maxArea = Math.max(maxArea,height[stack.pop()]*(i-stack.peek()-1));
}
stack.push(i);
}
while(stack.peek()!=-1){
maxArea = Math.max(maxArea,height[stack.pop()]*(height.length-stack.peek()-1));
}
return maxArea;
}
}