题目描述:
给定一个由 0 和 1 组成的矩阵 matrix ,找出只包含 1 的最大矩形,并返回其面积。
注意:此题 matrix 输入格式为一维 01 字符串数组。
示例 1:
输入:matrix = ["10100","10111","11111","10010"]
输出:6
解释:最大矩形如上图所示。
示例 2:
输入:matrix = []
输出:0
示例 3:
输入:matrix = ["0"]
输出:0
示例 4:
输入:matrix = ["1"]
输出:1
示例 5:
输入:matrix = ["00"]
输出:0
提示:
rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 为 '0' 或 '1'
做题记录:
1:这道题可以转换为在矩阵中找出直方图,通过计算直方图的最大面积来计算矩形的最大面积
2:以矩阵中的每一行为基线,可以得到4个直方图,然后取直方图的面积最大值(剑指 Offer II 039. 直方图最大矩形面积)。
做题记录:
public static int maximalRectangle(String[] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length() == 0) {
return 0;
}
int maxArea = 0;
int[] heights = new int[matrix[0].length()];
int m = matrix.length;
int n = matrix[0].length();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
heights[j] = matrix[i].charAt(j) == '0' ? 0 : heights[j] + 1;
}
maxArea = Math.max(maxArea, largestRectangleArea(heights));
}
return maxArea;
}
public static int largestRectangleArea(int[] heights) {
int maxArea = 0;
int[] nums = new int[heights.length + 2];
for (int i = 0; i < heights.length; i++) {
nums[i + 1] = heights[i];
}
heights = nums;
Stack<Integer> stack = new Stack<>();
stack.push(0);
for (int i = 1; i < heights.length; i++) {
while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) {
int index = stack.pop();
int height = nums[index];
int weight = i - stack.peek() - 1;
maxArea = Math.max(maxArea, height * weight);
}
stack.push(i);
}
return maxArea;
}