努橙刷题编

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

思路一:这道题和前面那道 84. Largest Rectangle in Histogram 类似,遍历二维数组,生成一个 heights 数组,然后用 Largest Rectangle in Histogram 一样的方法做。

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

 

思路二:Dynamic Programming - https://discuss.leetcode.com/topic/6650/share-my-dp-solution

posted on 2017-06-01 00:44  努橙  阅读(150)  评论(0编辑  收藏  举报