单调栈解法
问题可以转换为leetcide 84题的单调栈解法。
思路就是建立跟84题一样的图。84题的图是怎么存的?定义一个heights数组,数组元素是高度。同理,遍历该题的每一行,建立一个类似的图,然后进行求解即可。
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size() == 0) return 0; //注意特判
vector<vector<int>> heights(matrix.size(), vector<int>(matrix[0].size(), 0));
for (int i = 0; i < matrix.size(); i ++) {
for (int j = 0; j < matrix[0].size(); j ++) {
if (matrix[i][j] == '1') {
if (i == 0) heights[i][j] = 1;
else heights[i][j] = heights[i - 1][j] + 1;
} else {
heights[i][j] = 0;
}
}
}
//建立哨兵
for (int i = 0; i < matrix.size(); i ++) {
heights[i].insert(heights[i].begin(), 0);
heights[i].push_back(0);
}
int maxS = 0;
stack<int> st;
for (int i = 0; i < heights.size(); i ++) {
st.push(0);
for (int j = 1; j < heights[i].size(); j ++) {
while (heights[i][st.top()] > heights[i][j]) {
int hei = heights[i][st.top()]; st.pop();
int wid = j - st.top() - 1;
maxS = max(maxS, hei * wid);
}
st.push(j);
}
while (!st.empty()) st.pop();
}
return maxS;
}
};
可以进行优化。heights数组没必要全部求出来,即计算完一行之后,这一行就不需要了,可以删去。
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size() == 0) return 0;
int maxS = 0;
stack<int> st;
vector<int> heights(matrix[0].size() + 2);
heights[0] = 0;
heights[matrix[0].size() + 1] = 0;
for (int i = 0; i < matrix.size(); i ++) {
st.push(0);
for (int j = 0; j <= matrix[0].size(); j ++) {
if (j != matrix[0].size()) {
if (matrix[i][j] == '1') {
if (i == 0) heights[j + 1] = 1;
else heights[j + 1] = heights[j + 1] + 1;
} else {
heights[j + 1] = 0;
}
}
while (heights[st.top()] > heights[j + 1]) {
int hei = heights[st.top()]; st.pop();
int wid = j - st.top();
maxS = max(maxS, hei * wid);
}
st.push(j + 1);
}
while (!st.empty()) st.pop();
}
return maxS;
}
};