[leetCode] Maximal Rectangle

来源:互联网 发布:oracle数据库索引 编辑:程序博客网 时间:2024/05/17 06:56

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

public class Solution {    public int maximalRectangle(char[][] matrix) {        if (matrix.length == 0) return 0;        int row = matrix.length;        int col = matrix[0].length;        int[] height = new int[col];        int[] left = new int[col];        int[] right = new int[col];        int res = 0;        Arrays.fill(height, 0); Arrays.fill(left, 0); Arrays.fill(right, col);        for (int i = 0; i < row; i++) {            int curLeft = 0, curRight = col;            for (int j = 0; j < col; j++) {                if (matrix[i][j] == '1') {                    height[j]++;                    left[j] = Math.max(left[j], curLeft);                }                else {                    height[j] = 0;                    left[j] = 0;                    curLeft = j + 1;                }            }            for (int j = col - 1; j >= 0; j--) {                if (matrix[i][j] == '1') {                    right[j] = Math.min(right[j], curRight);                }                else {                    right[j] = col;                    curRight = j;                }                res = Math.max(res, (right[j] - left[j]) * height[j]);            }        }        return res;    }}


0 0
原创粉丝点击