题意:

image.png

解题思路:

  1. 思路:单调栈 Omn
  2. 1. 循环求出每一层的 heights[] 然后传给84题的函数即可;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String[][] $matrix
  4. * @return Integer
  5. */
  6. function maximalRectangle($matrix) {
  7. $res = 0;
  8. $heights = [];
  9. for ($i = 0; $i < count($matrix); $i++) {
  10. for ($j = 0; $j < count($matrix[0]); $j++) {
  11. if ($i == 0) {
  12. $heights[$j] = $matrix[$i][$j] == 0 ? 0 : 1;
  13. } else {
  14. $heights[$j] = $matrix[$i][$j] == 0 ? 0 : (1 + $heights[$j]);
  15. }
  16. }
  17. $res = max($res, $this->area($heights));
  18. }
  19. return $res;
  20. }
  21. function area($heights) {
  22. array_push($heights, - 1);
  23. $stack = new SplStack;
  24. $max = 0;
  25. for ($i = 0; $i < count($heights); $i++) {
  26. while (!$stack->isEmpty() && $heights[$stack->top()] >= $heights[$i]) {
  27. $last = $stack->pop();
  28. if (!$stack->isEmpty()) {
  29. $width = $i - $stack->top() - 1;
  30. } else {
  31. $width = $i;
  32. }
  33. $max = max($max, $heights[$last] * $width);
  34. }
  35. $stack->push($i);
  36. }
  37. return $max;
  38. }
  39. }

GO代码实现:

  1. //单调栈实现
  2. func maximalRectangle(matrix [][]byte) int {
  3. if matrix==nil || len(matrix)==0 {
  4. return 0
  5. }
  6. max := 0
  7. m, n := len(matrix), len(matrix[0])
  8. height := make([]int,n)
  9. for i := 0; i < m; i++ {
  10. for j := 0; j < n; j++ {
  11. if matrix[i][j] == '0' {
  12. height[j] = 0
  13. } else {
  14. height[j] = height[j] + 1
  15. }
  16. }
  17. max = int(math.Max(float64(max), float64(maxRectangle(height))))
  18. }
  19. return max
  20. }
  21. //84题的结果
  22. func maxRectangle(heights []int)int{
  23. if len(heights) == 0 {
  24. return 0
  25. }
  26. stack := make([]int, 0)
  27. max := 0
  28. for i := 0; i <= len(heights); i++ {
  29. cur := 0
  30. if i != len(heights) {
  31. cur = heights[i]
  32. }
  33. // 当前高度小于栈,则将栈内元素都弹出计算面积
  34. for len(stack) != 0 && cur <= heights[stack[len(stack)-1]] {
  35. pop := stack[len(stack)-1]
  36. stack = stack[:len(stack)-1]
  37. h := heights[pop]
  38. // 计算宽度
  39. w := i
  40. if len(stack) != 0 {
  41. peek := stack[len(stack)-1]
  42. w = i - peek - 1
  43. }
  44. max = Max(max, h*w)
  45. }
  46. stack = append(stack, i)
  47. }
  48. return max
  49. }
  50. func Max(a, b int) int {
  51. if a > b {
  52. return a
  53. }
  54. return b
  55. }