findingsea's Studio.

Maximal Rectangle@LeetCode

Word count: 300 / Reading time: 2 min
2015/04/16 Share

Maximal Rectangle

这一题的核心算法其实和Largest Rectangle in Histogram一样,对每一行都求出每个元素对应的高度,这个高度就是对应的连续1的长度,然后对每一行都更新一次最大矩形面积,那么这个问题就变成了Largest Rectangle in Histogram,用相同的方法求解就行了。总结来说就是对矩阵中的每一行,执行一遍Largest Rectangle in Histogram算法。

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0)
return 0;
int largestRectangle = 0;
int[] height = new int[matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
int h = matrix[i][j] - '0';
height[j] = h == 0 ? 0 : height[j] + 1;
}
largestRectangle = Math.max(largestRectangle, largestRectangleArea(height));
}
return largestRectangle;
}

private int largestRectangleArea(int[] height) {
Stack<Integer> stack = new Stack<Integer>();
int index = 0, largestArea = 0;
while (index < height.length) {
if (stack.isEmpty() || height[stack.peek()] < height[index]) {
stack.push(index++);
} else {
int h = height[stack.pop()];
int w = stack.isEmpty() ? index : index - stack.peek() - 1;
largestArea = Math.max(largestArea, h * w);
}
}
while (!stack.isEmpty()) {
int h = height[stack.pop()];
int w = stack.isEmpty() ? height.length : height.length - stack.peek() - 1;
largestArea = Math.max(largestArea, h * w);
}
return largestArea;
}
}
CATALOG
  1. 1. Maximal Rectangle