思路:html
分別按行拆分後將這一行以前的每列疊加起來,而後使用leetcode84http://www.javashuo.com/article/p-hfawwtcx-gt.html的思路計算。c++
實現:spa
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 class Solution 5 { 6 public: 7 int maximalRectangle(vector<vector<char>>& matrix) 8 { 9 int n = matrix.size(); if (n == 0) return 0; 10 int m = matrix[0].size(); if (m == 0) return 0; 11 int ans = 0; 12 vector<int> h(m, 0), l(m, 0), r(m, 0); 13 for (int i = 0; i < n; i++) 14 { 15 for (int j = 0; j < m; j++) 16 { 17 h[j] = (matrix[i][j] == '0' ? 0 : h[j] + 1); 18 } 19 stack<int> s; 20 for (int j = 0; j < m; j++) 21 { 22 while (!s.empty() && h[s.top()] >= h[j]) s.pop(); 23 l[j] = (s.empty() ? 0 : s.top() + 1); 24 s.push(j); 25 } 26 while (!s.empty()) s.pop(); 27 for (int j = m - 1; j >= 0; j--) 28 { 29 while (!s.empty() && h[s.top()] >= h[j]) s.pop(); 30 r[j] = (s.empty() ? m - 1 : s.top() - 1); 31 s.push(j); 32 } 33 for (int j = 0; j < m; j++) 34 { 35 ans = max(ans, (r[j] - l[j] + 1) * h[j]); 36 } 37 } 38 return ans; 39 } 40 }; 41 int main() 42 { 43 char a[][5] = {{'1','0','1','0','0'}, 44 {'1','0','1','1','1'}, 45 {'1','1','1','1','1'}, 46 {'1','0','0','1','0'}}; 47 // char a[][4] = {{'1','1','1','1'}, 48 // {'1','1','1','1'}, 49 // {'1','1','1','1'}}; 50 vector<vector<char>> v; 51 for (int i = 0; i < 4; i++) 52 { 53 v.push_back(vector<char>(a[i], a[i] + 5)); 54 } 55 cout << Solution().maximalRectangle(v) << endl; 56 return 0; 57 }