这是一道很难的题,开始想用dp来解决,想了半天也没想通转移方程该怎么写,看了别人的博客才发现这道题可以和84题Largest Rectangle in Histogram 关联起来。把矩阵从上到下一行一行去切,只看上面的部分就可以发现其实可以转化成对每一行球第84题解的过程。但是我第84题是直接搜索每一列然后再左右搜索找到比那一列小的列为止然后计算通过的,这种复杂度比较高,我看了一下别人的解法,可以用栈来解决,这样问题只有线性的复杂度,然后对每行在求解,也不会有太高的时间复杂度。
代码如下:
class Solution {
public int maximalRectangle(char[][] matrix) {
int kuan=matrix.length;
if (kuan==0) return 0;
int chang=matrix[0].length;
int max=0;
int []height=new int[chang];
for(int i=0;i<kuan;i++)
{
for (int j=0;j<chang;j++)
{
if (matrix[i][j]=='1')
{
height[j]+=1;
}
else height[j]=0;
}
if (Cal(height)>max) max=Cal(height);
}
return max;
}
public int Cal(int []height) //采用第84题的新解法(栈)来解决
{
Stack<Integer> stk=new Stack<Integer>();
int max=0;
for (int i=0;i<height.length;i++)
{
if (stk.empty()||height[i]>=stk.peek())
{
stk.push(height[i]);
}
else
{
int count=0;
while (!stk.empty() && stk.peek()>height[i])
{
int index=stk.pop();
count++;
if (count*index>max) max=count*index;
}
while (count!=0)
{
count--;
stk.push(height[i]);
}
stk.push(height[i]);
}
}
int count=0;
while (!stk.empty())
{
int index=stk.pop();
count++;
if (count*index>max) max=count*index;
}
return max;
}
}