[Leetcode] 85. Maximal Rectangle

来源:互联网 发布:淘宝联盟的导购推广位 编辑:程序博客网 时间:2024/04/27 23:32

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

import java.util.Stack;public class Solution {    public int maximalRectangle(char[][] matrix) {        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;        int max = 0;        int[] height = new int[matrix[0].length];        for(int i = 0; i < matrix.length; i++){            for(int j = 0; j < matrix[i].length; j++){                if(matrix[i][j] == '1'){                    height[j]++;                } else {                    height[j] = 0;                }            }            max = Math.max(max, largestRectangleArea(height));        }        return max;    }    private int largestRectangleArea(int[] height) {        if(height == null || height.length == 0) return 0;        int max = 0;        Stack<Integer> stack = new Stack<Integer>();        for(int i = 0; i <= height.length; i++){            int currentH = (i == height.length? -1: height[i]);            while(!stack.isEmpty() && height[stack.peek()] > currentH){                int h = height[stack.pop()];                int w = stack.isEmpty()? i: i - stack.peek() - 1;                max = Math.max(max, h * w);            }            stack.push(i);        }        return max;    }}


0 0
原创粉丝点击