leetcode_1614嵌套括号的最大深度

1. 题意

给定 有效括号字符串 s,返回 s 的 嵌套深度。嵌套深度是嵌套括号的 最大 数量。

2. 题解

其实就是求未闭合的左括号的最大数量!

可以用栈来解决!

2.1 老实人解法

左括号入栈,右括号就把这前的左括号出栈!

在整个过程中取栈的最大深度。

cpp 复制代码
class Solution {
public:
    int maxDepth(string s) {
        
        int sz = static_cast<int>( s.size() );

        stack<char> st{};

        int ans{};
        for(char c:s) {
            if ( c == '(') {
                st.push( '(');
            }
            else if ( c == ')') {
                st.pop();
            }
            else {

            }
            ans = max( ans, static_cast<int>(st.size()) );
        }

        return ans;
    }
};
2.2 坏人做法

其实不需要真的入栈,只需要在左括号入栈时增加栈深度,而在右括号出现时减少栈的深度就可以了。

cpp 复制代码
class Solution {
public:
    int maxDepth(string s) {
        
        int sz = static_cast<int>( s.size() );

        int depth{};

        int ans{};
        for(char c:s) {
            if ( c == '(') {
                depth++;
            }
            else if ( c == ')') {
                depth--;
            }
            else {

            }
            ans = max( ans, depth );
        }

        return ans;
    }
};
相关推荐
liulilittle5 小时前
认识麻将 —— 流水及对账
算法·游戏·lua·对账·流水·资金·玩法
郝学胜-神的一滴9 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
嵌入式 Linux手记20 小时前
柔性数组:为什么写 data[] 而不是 data[0]
linux·c语言·面试·职场和发展·嵌入式·柔性数组
青少儿编程课堂1 天前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛
geovindu1 天前
python: KNeighborsClassifier K
开发语言·后端·python·算法
让我们一起加油好吗1 天前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
凌冰_1 天前
数据结构 - 队列(五)
数据结构·算法·软件工程
让我们一起加油好吗1 天前
【数据结构】ST 表
数据结构·c++·算法·动态规划·洛谷·st表
让我们一起加油好吗1 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试