Maximal Rectangle

这个题和Largest rectangle in histogram有异曲同工之妙, 把每一行上面的矩形看成是histogram就行了

代码如下:

public class Solution {
    public int maximalRectangle(char[][] matrix) {
		if(matrix==null||matrix.length==0)
			return 0;
		int maxArea=0,m=matrix.length,n=matrix[0].length;
		for(int i=0;i<m;i++){
			Stack<Integer> heightStack=new Stack<Integer>();
			Stack<Integer> indexStack=new Stack<Integer>();
			for(int j=0;j<n;j++){
				int hIndex=i,h=0;
				int[] heights=new int[n];
				while(hIndex>=0&&matrix[hIndex--][j]=='1')
					h++;
				heights[j]=h;
				if(heightStack.isEmpty()||heights[j]>=heightStack.peek()){
					heightStack.add(heights[j]);
					indexStack.add(j);
				}else{
				    //这个index非常重要,是下面用来计算的
					int index=0;
					while(!heightStack.isEmpty()&&heightStack.peek()>heights[j]){
						index=indexStack.pop();
						int area=(j-index)*heightStack.pop();
						maxArea=area>maxArea?area:maxArea;
					}
					heightStack.add(heights[j]);
					indexStack.add(index);
				}
			}
			while(!heightStack.isEmpty()){
				int area=(n-indexStack.pop())*heightStack.pop();
				maxArea=area>maxArea?area:maxArea;
			}
		}
		return maxArea; 
    }
}


你可能感兴趣的:(java,LeetCode,stack)