public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0|| matrix[0] == null || matrix[0].length == 0) {
return 0;
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] heightMatrix = new int[rows][cols];
for (int i = 0; i < cols; i++) {
heightMatrix[0][i] = (matrix[0][i] == '0') ? 0 : 1;
}
for (int i = 1; i < rows; i++) {
for (int j = 0; j < cols; j++) {
heightMatrix[i][j] = (matrix[i][j] == '0') ? 0 : heightMatrix[i - 1][j] + 1;
}
}
int maxArea = 0;
for (int[] row: heightMatrix) {
int currMax = largestRectangleArea(row);
maxArea = Math.max(maxArea, currMax);
}
return maxArea;
}
// 84 Largest Rectangle in Histogram 题解 function
private int largestRectangleArea(int[] heights) {
if (heights == null || heights.length == 0) {
return 0;
}
int maxArea = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i <= heights.length; i++) {
int h = (i == heights.length) ? 0 : heights[i];
while (!stack.isEmpty() && heights[stack.peek()] > h) {
int index = stack.pop();
int leftBound = stack.isEmpty() ? -1 : stack.peek();
int currArea = (i - leftBound - 1) * heights[index];
maxArea = Math.max(maxArea, currArea);
}
stack.push(i);
}
return maxArea;
}
85. Maximal Rectangle
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...