您的位置:首页 > 其它

Leetcode 85. Maximal Rectangle

2016-04-10 21:10 225 查看

Question

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.

Code

public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}

int rows = matrix.length;
int cols = matrix[0].length;

int[][] h = new int[rows][cols];

int max = 0;

for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {

h[i][j] = matrix[i][j] == '1' ? 1: 0;

if (i != 0 && h[i][j] != 0) {
h[i][j] = h[i - 1][j] + 1;
}

if (j == cols - 1) {
max = Math.max(max, maxArea(h[i]));
}
}
}

return max;
}

public int maxArea(int[] h) {
Stack<Integer> s = new Stack<Integer>();

int max = 0;
int i = 0;

// 注意,这里使用<= 因为当i到达最后,需要计算一次。
while (i <= h.length) {
//
if (s.isEmpty() || i < h.length && h[i] >= h[s.peek()]) {
s.push(i);
i++;
} else {
int height = h[s.pop()];
int width = s.isEmpty() ? i: i - s.peek() - 1;
max = Math.max(max, height * width);
}
}

return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: