您的位置:首页 > 其它

Leetcode Maximal Rectangle

2016-07-20 03:46 363 查看
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

Difficulty: Hard

Solution: http://www.programcreek.com/2014/05/leetcode-maximal-rectangle-java/

public class Solution {
public int helper(int[] height){
Stack<Integer> stack = new Stack<Integer>();
int i = 0, ans = 0;
while(i < height.length){
if(stack.isEmpty() || height[i] >= height[stack.peek()]){
stack.push(i);
i++;
}
else{
int temp = stack.pop();
ans = Math.max(ans, height[temp] * (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return ans;

}
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
if(m == 0) return 0;
int n = matrix[0].length;
int ans = 0;
int[][] nums = new int[m][n + 1];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0 && matrix[i][j] == '1'){
nums[i][j] = 1;
}
else if(matrix[i][j] == '1'){
nums[i][j] = 1 + nums[i-1][j];
}
}
}
for(int i = 0; i < m; i++){
ans = Math.max(ans, helper(nums[i]));
}
return ans;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: