13.4 Maximal Rectangle

来源:互联网 发布:网络诈骗有哪些形式 编辑:程序博客网 时间:2024/06/05 16:35

Link: https://oj.leetcode.com/problems/maximal-rectangle/

Time: O(m*n), Space: O(n)

This question is very difficult. I refered to http://blog.csdn.net/linhuanmars/article/details/20524507,and coded by myself.

The subroutine of this Q is based on Largest Rectangle Area 

public class Solution {    public int maximalRectangle(char[][] matrix) {        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){            return 0;        }        //find the largestRectangleArea for the area above each row        int[] height = new int[matrix[0].length];        int maxRec = 0;        for(int i = 0; i < matrix.length; i++){            for(int j = 0; j < matrix[0].length; j++){                height[j] = matrix[i][j] == '0' ? 0 : height[j]+1;            }            maxRec = Math.max(maxRec, largestRectangleArea(height));        }        return maxRec;    }        public int largestRectangleArea(int[] height){        Stack<Integer> stack = new Stack<Integer>();        int i = 0;        int maxArea = 0;        int[] h = new int[height.length+1];        h = Arrays.copyOf(height, height.length+1);        while(i < h.length){            //stack stores indices with increasing heights            if(stack.isEmpty() || h[stack.peek()]<h[i]){                stack.push(i);                i++;            }            else{                int t = stack.pop();                maxArea = Math.max(maxArea, h[t] * (stack.isEmpty()? i : i - stack.peek()-1));            }        }        return maxArea;    }}


Question: Why do we times "i" to h[t] when stack.isEmpty()  whencomputing maxArea? 


0 0
原创粉丝点击