《leetCode》: Maximal Rectangle

题目

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

思路

这个题目确实比较难,做不出来,在讨论组看到的别人的解法,借助了上一个题的思路。

public int maximalRectangle(char[][] matrix) {
        if(matrix==null||matrix.length<1||matrix[0].length<1){
            return 0;
        }
        int height[]=new int[matrix[0].length];
        for(int i=0;i<matrix[0].length;i++){
            if(matrix[0][i]=='1'){
                height[i]=1;
            }
        }
        int res=largestInLine(height);
        for(int row=1;row<matrix.length;row++){
            for(int col=0;col<matrix[0].length;col++){
                if(matrix[row][col]=='1'){
                    height[col]++;
                }
                else{
                    height[col]=0;
                }
            }
            res=Math.max(res,largestInLine(height));
        }
        return res;
    }

    public int largestInLine(int[] height) {
        if(height == null || height.length == 0) return 0;
        int len = height.length;
        Stack<Integer> s = new Stack<Integer>();
        int maxArea = 0;
        for(int i = 0; i <= len; i++){
            int h = (i == len ? 0 : height[i]);
            if(s.isEmpty() || h >= height[s.peek()]){
                s.push(i);
            }else{
                int tp = s.pop();
                maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
                i--;
            }
        }
        return maxArea;
    }

你可能感兴趣的:(LeetCode,Matrix,2d)