leetcode 最大正方形 中等
有两种方法:
① 二分 + 前缀和。枚举每个点作为起点,二分正方形边长,利用前缀和判断当前的正方形是否全 1 即可。
② 单调栈。有一个最大全 1 的矩形题目,而最大正方形肯定被最大矩形包含,假设最大矩形长宽为 a, b,那么每一次找到的一个当前行的最大矩形时,ans = max(ans, min(a, b)).
最大全 1 矩形参考:https://blog.csdn.net/zuzhiang/article/details/78693421
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.empty() || matrix[0].empty()) return 0; vector<vector<int>> height(matrix.size()); for(auto &item : height) { item.resize(matrix[0].size(), 0); } for(int i = 0; i < height.size(); ++ i) { for(int j = 0; j < height[0].size(); ++ j) { if(matrix[i][j] == '0') continue; height[i][j] = i > 0 ? height[i - 1][j] + 1 : 1; } } int ans = 0; stack<int> stk; for(int i = 0; i < height.size(); ++ i) { while(!stk.empty()) stk.pop(); height[i].emplace_back(0); for(int j = 0; j < height[i].size(); ++ j) { if(stk.empty() || height[i][stk.top()] <= height[i][j]) { stk.push(j); continue; } int lef, rig = j - 1; while(!stk.empty() && height[i][stk.top()] > height[i][j]) { lef = stk.top(); stk.pop(); ans = max(ans, min(rig - lef + 1, height[i][lef])); } height[i][lef] = height[i][j]; stk.push(lef); } } return ans * ans; } };