public class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int r = matrix.length, c = matrix[0].length;
int[][] heights = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (i == 0) {
heights[i][j] = matrix[i][j] - '0';
} else {
if (matrix[i][j] != '0') {
heights[i][j] = 1 + heights[i - 1][j];
}
}
}
}
int maxArea = 0;
for (int i = 0; i < r; i++) {
Stack<Integer> stack = new Stack<>();
for (int j = 0; j < c; j++) {
if (stack.isEmpty()) {
stack.push(j);
} else {
//int h = heights[i][stack.peek()];
while (!stack.isEmpty() && heights[i][j] < heights[i][stack.peek()]) {
//int maxH = stack.pop();
int maxH = heights[i][stack.pop()];
if (!stack.isEmpty()) {
maxArea = Math.max(maxArea, (j - 1 - stack.peek())*maxH);
} else {
maxArea = Math.max(maxArea, (j)*maxH);
}
}
stack.push(j);
}
}
while (!stack.isEmpty()) {
int h = heights[i][stack.pop()];
if (!stack.isEmpty()) {
maxArea = Math.max(maxArea, (c - 1 - stack.peek())*h);
} else {
maxArea = Math.max(maxArea, c*h);
}
}
}
return maxArea;
}
}
Maximal Rectangle
最新推荐文章于 2021-10-17 09:55:57 发布