85. Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 6.
本题比较难,主要从长方形入手,用一个一维数组来记录从第0行到该行该列的出现连续1个个数,如果该位置没有出现1,则为0.依次遍历每一行,每一行都定义一个stack,用来储存stack.peek()<=h[i]的序列,如果h[i]<stack.peek(),则计算stack里面大于h[i]的长方形面积,值得注意的是,要考虑好stack里面最后一个元素,即为整个一行里面元素高最小的元素,这个时候算面积需要算i*stack.peek();代码如下:
public class Solution {
public int maximalRectangle(char[][] matrix) {
int max = 0;
if(matrix==null||matrix.length==0||matrix[0].length==0) return max;
int m =matrix.length;
int n = matrix[0].length;
int[] h = new int[n+1];
for(int i=0;i<m;i++){
Stack<Integer> stack =new Stack<Integer>();
for(int j=0;j<n+1;j++){
if(j<n&&matrix[i][j]=='1'){
h[j]++;
}else{
h[j]=0;
}
if(stack.isEmpty()||h[stack.peek()]<=h[j]){
stack.push(j);
}else{
while(!stack.isEmpty()&&h[stack.peek()]>h[j]){
int top = stack.pop();
int area = h[top]*(stack.isEmpty()?j:j-1-stack.peek());
max = Math.max(max,area);
}
stack.push(j);
}
}
}
return max;
}
}