AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

LeetCode 221. Maximal Square    原题链接    中等

作者: 作者的头像   邓泽军 ,  2019-09-13 01:20:56 ,  所有人可见 ,  阅读 1357


1


2

题目描述

单调栈:LeetCode 42 和 85 题基本一样。将矩阵看成一个二维矩阵,以每一行为x轴,h[j]是该列的高度。

C++ 代码

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int n = matrix.size();
        if (!n) return 0;
        int m = matrix[0].size();
        auto a = matrix;
        vector<int> h(m + 1, 0);
        int res = 0;
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++){
                if (a[i][j] == '0') h[j] = 0;
                else h[j] ++;
            }
            stack<int> st;
            h[m] = -1;//确保所有元素出栈。
            for (int j = 0; j <= m; j ++) {
                while (st.size() && h[st.top()] >= h[j]) {
                    int cur = st.top(); st.pop();
                    int w = st.empty() ? j : j - st.top() - 1;
                    if (w <= h[cur]) 
                        res = max(res, w * w);//如果长比宽大,那么就是宽的平方。
                    else 
                        res = max(res, h[cur] * h[cur]);
                }
                st.push(j);
            }
        }
        return res;
    }
};

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息