题目描述:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
主要是注意 公式中宽度的求取:
import java.util.*;
//本题是求直方图中最大矩形面积的变形
public class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix==null||matrix.length==0||matrix[0].length==0)
return 0;
Stack<Integer> stack=new Stack<>();
stack.push(-1);
int row=matrix.length;
int col=matrix[0].length;
int high[]=new int[col];
int max=0;
for(int i=0;i<row;i++){
//将点抽象成矩形的面积,构建模型
for(int j=0;j<col;j++){
if(matrix[i][j]=='0')
high[j]=0;
else
high[j]+=1;
}
for(int j=0;j<col;j++){
while(stack.peek()!=-1&&high[j]<high[stack.peek()]){
int topIndex=stack.pop();
max=Math.max(max,(j-1-stack.peek())*high[topIndex]);
/*一切都是为了这个公式做铺垫
一定要注意 宽度 是 j-1-stack.peek() 而不能用 j-topIndex
因为 若存在栈中的两个下标中可能存在不连续的情况
出现不连续的情况的原因是 中间 断了的高度是高于 右边的
所以 求 删除节点的 面积的时候 ,是先 删除这个节点,然后找到删除节点的前一个节点,这两者中间的宽度才是真实的宽度!
*/
}
stack.push(j);
}
while(stack.peek()!=-1){
int topIndex=stack.pop();
max=Math.max(max,(col-1-stack.peek())*high[topIndex]);
}
}
return max;
}
}