题目描述

image.png

解题思路

其他解法

参照官解:https://leetcode.cn/problems/maximal-rectangle/solution/zui-da-ju-xing-by-leetcode-solution-bjlu/

单调栈解法

可以直观的看见每一层相当于求一次最大的矩形面积,所以每一层都遍历一遍,使用一个变量记录最大的即可,每一层如何操作参照84.柱状图中最大的矩形的几种做法都可以求!!!直接照搬即可,就是转化一下。
image.png
所以本题重要的是表示高度,2次遍历,使用一个一维数组来记录高度。

  1. class Solution {
  2. public int maximalRectangle(char[][] matrix) {
  3. if (matrix.length == 0) return 0;
  4. int[] height = new int[matrix[0].length];
  5. int maxSize = 0;
  6. for (int i = 0; i < matrix.length; i++) {
  7. for (int j = 0; j < matrix[0].length; j++) {
  8. if (matrix[i][j] == '1') {
  9. height[j] += 1;
  10. }else {
  11. height[j] = 0;
  12. }
  13. }
  14. maxSize = Math.max(largestRectangleArea(height), maxSize);
  15. }
  16. return maxSize;
  17. }
  18. public int largestRectangleArea(int[] heights) {
  19. if (heights.length == 0) return 0;
  20. Stack<Integer> stack = new Stack<>();
  21. int size = 0;
  22. int[] newHeights = new int[heights.length + 2];
  23. for (int i = 0; i < heights.length; i++) {
  24. newHeights[i + 1] = heights[i];
  25. }
  26. heights = newHeights;
  27. stack.push(0);
  28. for (int i = 1; i < heights.length; i++) {
  29. if (heights[stack.peek()] <= heights[i]) {
  30. stack.push(i);
  31. } else if (heights[stack.peek()] > heights[i]) {
  32. while (heights[stack.peek()] > heights[i]) {
  33. int height = heights[stack.peek()];
  34. stack.pop();
  35. int left = stack.peek();
  36. int width = i - left - 1;
  37. size = Math.max(height * width, size);
  38. }
  39. stack.push(i);
  40. }
  41. }
  42. return size;
  43. }
  44. }