解题思路:
这道题是84题的拓展,还是用单调栈,然后每一排都求一次单调栈,并实时更新最大值即可。
提交代码:
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length==0||matrix[0].length==0) return 0;
int[][] heights = new int[matrix.length][matrix[0].length];
Stack<Integer> stack=new Stack<Integer>();
int maxSize=0;
// create the total heights of each rows
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (i == 0) {
if (matrix[i][j] == '1')
heights[i][j] = 1;
else
heights[i][j] = 0;
} else {
if (matrix[i][j] == '1')
heights[i][j] = heights[i - 1][j] + 1;
else
heights[i][j] = 0;
}
}
}
//calculate maxSize in each row
for(int i=0;i<matrix.length;i++) {
stack.clear();
int j=0,curHeight,curLength,curSize;
int[] h=new int[matrix[0].length+1];
h=Arrays.copyOf(heights[i], matrix[0].length+1);
while(j<h.length) {
if(stack.isEmpty()||h[stack.peek()]<h[j])
stack.push(j++);
else {
curHeight=h[stack.pop()];
curLength=stack.isEmpty()?j:(j-stack.peek()-1);
curSize=curHeight*curLength;
if(curSize>maxSize) maxSize=curSize;
}
}
}
return maxSize;
}
}
运行结果:

本文介绍了一种使用单调栈解决矩阵中寻找最大全'1'矩形的方法。通过为每一行创建高度数组并应用单调栈,实时更新最大矩形面积,最终返回矩阵中的最大矩形面积。
603

被折叠的 条评论
为什么被折叠?



