leetcode.85. Maximal Rectangle

来源:互联网 发布:淘宝的延长收货是几天 编辑:程序博客网 时间:2024/04/30 07:02

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

class Solution {public:    int maximalRectangle(vector<vector<char>>& matrix) {       if(matrix.size() == 0 || matrix[0].size() == 0)              return 0;                    int res = 0;         vector<int> height(matrix[0].size(), 0);         for(int i = 0; i < matrix.size(); ++ i)         {             for(int j = 0; j < matrix[0].size(); ++ j)                 height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1;             res = max(res, largestRectangleArea(height));         }         return res;     }    int largestRectangleArea(vector<int> &height)     {         int res = 0;         stack<int> si;         height.push_back(0);         for(int i = 0; i < height.size(); ++ i)         {             while(!si.empty() && height[si.top()] >= height[i])             {                 int h = height[si.top()];                 si.pop();                                  int s = h * (si.empty() ? i : (i - si.top() - 1));                 res = max(res, s);             }            si.push(i);         }         return res;     }};




0 0
原创粉丝点击