85. 最大矩形

  1. class Solution {
  2. public int maximalRectangle(char[][] matrix) {
  3. if (matrix.length == 0)
  4. return 0;
  5. int[] heights = new int[matrix[0].length];
  6. int max = 0;
  7. for (int i = 0; i < matrix.length; i++) {
  8. for (int j = 0; j < matrix[0].length; j++) {
  9. if (matrix[i][j] == '1') {
  10. heights[j] += 1;
  11. } else {
  12. heights[j] = 0;
  13. }
  14. }
  15. max = Math.max(max, largestRectangleArea(heights));
  16. }
  17. return max;
  18. }
  19. public int largestRectangleArea(int[] heights) {
  20. int len = heights.length;
  21. if (len == 0) {
  22. return 0;
  23. } else if (len == 1) {
  24. return heights[0];
  25. }
  26. int[] newHeigths = new int[len + 2];
  27. for (int i = 0; i < heights.length; i++) {
  28. newHeigths[i + 1] = heights[i];
  29. }
  30. heights = newHeigths;
  31. Deque<Integer> stack = new LinkedList<>();
  32. stack.push(0);
  33. int area = 0;
  34. for (int i = 1; i < heights.length; i++) {
  35. while (heights[i] < heights[stack.peek()]) {
  36. // 当前遍历到的严格小于栈顶的
  37. int height = heights[stack.pop()];
  38. int width = i - stack.peek() - 1;
  39. area = Math.max(area, width * height);
  40. }
  41. stack.push(i);
  42. }
  43. return area;
  44. }
  45. }