您的位置:首页 > 其它

leetcode Maximal Rectangle

2014-08-28 17:57 435 查看
此题参考

/article/5789868.html

虽然和作者的代码大同小异,但是用C++实现提交后一直提示Runtime Error

贴出不知道问题在哪的自己的代码

class Solution
{

public:
int maximalRectangle(vector<vector<char> > &matrix)
{
int rowNum = matrix.size();
int colNum = matrix[0].size();

if(rowNum==0||colNum==0)
return 0;

vector<vector<int> > height(rowNum, vector<int>(colNum+1));

int maxArea = 0;

for(int i = 0; i < rowNum; ++i)
for(int j = 0; j < colNum; ++j)
{
if(matrix[i][j]=='0')
height[i][j]=0;
else
{
height[i][j] = i==0 ? 1:height[i-1][j]+1;
}
}

for(int i = 0; i < rowNum; ++i)
{
int tempArea = maximalRectangleHelper(height[i]);
if(maxArea<tempArea)
maxArea = tempArea;
}

return maxArea;

}

int maximalRectangleHelper(vector<int> &height)
{
stack<int> heightStack;
int maxarea = 0;
int i = 0;

while(i<height.size())
{
if(heightStack.empty()||height[heightStack.top()]<=height[i])
{
heightStack.push(i);
++i;
}
else
{
int topIndex = heightStack.top();
heightStack.pop();
maxarea = max(maxarea, height[topIndex]*(heightStack.empty()?i:i-heightStack.top()-1));

}

}

return maxarea;

}

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