# [leetcode] 85. 最大矩形

85. 最大矩形

class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
if (n == 0) return 0;

int[] height = new int[n];
int ans = 0;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '0') height[j] = 0;
else if (matrix[i][j] == '1') height[j] += 1;
}
ans = Math.max(largestRectangleArea(height), ans);
}
return ans;
}

public int largestRectangleArea(int[] heights) {
if (heights.length == 0) return 0;
Stack<Integer> stack = new Stack<>();

int max = 0;
for (int i = 0; i < heights.length; i++) {
while (!stack.isEmpty() && heights[stack.peek()] >= heights[i]) {
int tmp = stack.pop();
// 把当前的tmp木板作为最短木板，看能组成的最大面积是多少
max = Math.max(max, heights[tmp] * (stack.empty() ? i : i - stack.peek() - 1));
}
stack.push(i);
}

int tmp = 0;
int len = heights.length;
while (!stack.isEmpty()) {
tmp = stack.pop();
max = Math.max(max, heights[tmp] * (stack.empty() ? len : len - stack.peek() - 1));
}

return max;
}
}


height数组和上面一样，height表示高，这里的left数组表示左边界是1的位置，right数组表示右边界是1的位置，那么对于任意一行的第j个位置，矩形为(right[j] - left[j]) * height[j]

posted @ 2018-07-31 23:52  ACBingo  阅读(...)  评论(...编辑  收藏