该题首先没有思路,然后看了题解发现与84题有异曲同工之妙。
基于栈的方法
该题可以通过矩阵构建直方图,对于下图:
每一行看成一个直方图,对行中每一个元素求高度,这里的高度指的是当前元素上面一共有多少个连续的1。然后采用第84题中的单调栈的方法。
但是需要注意,在每遍历一行后,栈中仍然存放一个元素,该元素是在即将退出循环时被加入的(算是这种实现方式的副产品),所以需要清除掉,否则会导致后面执行异常。
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length == 0) {
return 0;
}
int m = matrix.length, n = matrix[0].length, aws = 0, tmp, k;
int[] heights = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(matrix[i][j] == '1') {
++heights[j];
} else {
heights[j] = 0;
}
}
k = 0;
while(k <= n) {
if((k == n ? -1 : heights[k]) < (stack.isEmpty() ? -1 : heights[stack.getLast()])) {
if((tmp = heights[stack.pollLast()] * (k - (stack.isEmpty() ? 0 : stack.getLast() + 1))) > aws) {
aws = tmp;
}
} else {
stack.addLast(k++);
}
}
stack.pollLast();
}
return aws;
}
}