链接
给定一个由 0 和 1 组成的矩阵 matrix ,找出只包含 1 的最大矩形,并返回其面积。
注意:此题 matrix 输入格式为一维 01 字符串数组。
import java.util.Stack;
class Solution {
private static int getMax(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int ret = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < height.length; ++i) {
while (!stack.isEmpty() && height[stack.peek()] >= height[i]) {
Integer pop = stack.pop();
int left = stack.isEmpty() ? -1 : stack.peek();
ret = Math.max(ret, (i - left - 1) * height[pop]);
}
stack.push(i);
}
while (!stack.isEmpty()) {
Integer pop = stack.pop();
int left = stack.isEmpty() ? -1 : stack.peek();
ret = Math.max(ret, (height.length - left - 1) * height[pop]);
}
return ret;
}
public static int maximalRectangle(String[] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
int n = matrix.length;
int m = matrix[0].length();
int[] height = new int[m];
int ret = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
height[j] = matrix[i].charAt(j) == '1' ? 1 + height[j] : 0;
}
ret = Math.max(ret, getMax(height));
}
return ret;
}
public static void main(String[] args) {
String[] matrix = {"10100", "10111", "11111", "10010"};
System.out.println(maximalRectangle(matrix));
}
}