import java.util.*;
public class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length==0 || matrix[0].length==0 || matrix==null) return 0;
int[] height = new int[matrix[0].length]; //与列数有关
int res = 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; //只能统计连续的1,若不连续则一定清零
}
res = helper(height,res);
}
return res;
}
public int helper(int[] height , int res){
Stack<Integer> st = new Stack<Integer>();
for(int i=0;i<height.length;i++){
while(!st.empty() && height[st.peek()]>=height[i]){ //找到满足条件的i的插入位置
int top = st.pop(); //当前的栈顶
int left = st.empty()?-1:st.peek();
res = Math.max(res, height[top]*(i-left-1));
} //找寻i的恰当插入位置,并且及时更新当前的最优解
st.push(i);
}
while(!st.empty()){ //剩余部分的左边界即为st.top(),右边界是n-1
int top = st.pop();
int left = st.empty()?-1:st.peek();
res = Math.max(res,height[top]*(height.length-1-left));
}
return res;
}
}
最大子矩阵
最新推荐文章于 2020-10-05 22:27:19 发布