Maximal Rectangle

来源:互联网 发布:逗号,在c语言里是什么 编辑:程序博客网 时间:2024/05/17 07:06
public class Solution {    public int maximalRectangle(char[][] matrix) {        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {            return 0;        }        int r = matrix.length, c = matrix[0].length;        int[][] heights = new int[r][c];        for (int i = 0; i < r; i++) {            for (int j = 0; j < c; j++) {                if (i == 0) {                    heights[i][j] = matrix[i][j] - '0';                } else {                    if (matrix[i][j] != '0') {                        heights[i][j] = 1 + heights[i - 1][j];                    }                   }            }        }        int maxArea = 0;        for (int i = 0; i < r; i++) {            Stack<Integer> stack = new Stack<>();            for (int j = 0; j < c; j++) {                if (stack.isEmpty()) {                    stack.push(j);                } else {                    //int h = heights[i][stack.peek()];                    while (!stack.isEmpty() && heights[i][j] < heights[i][stack.peek()]) {                        //int maxH = stack.pop();                        int maxH = heights[i][stack.pop()];                        if (!stack.isEmpty()) {                            maxArea = Math.max(maxArea, (j - 1 - stack.peek())*maxH);                        } else {                            maxArea = Math.max(maxArea, (j)*maxH);                        }                    }                    stack.push(j);                }            }            while (!stack.isEmpty()) {                int h = heights[i][stack.pop()];                if (!stack.isEmpty()) {                    maxArea = Math.max(maxArea, (c - 1 - stack.peek())*h);                } else {                    maxArea = Math.max(maxArea, c*h);                }            }        }        return maxArea;    }}

0 0