# LeetCode 1614、括号的最大嵌套深度
# 一、题目描述
如果字符串满足以下条件之一,则可以称之为 有效括号字符串*(valid parentheses string,可以简写为 VPS):
- 字符串是一个空字符串
"",或者是一个不为"("或")"的单字符。 - 字符串可以写为
AB(A与B字符串连接),其中A和B都是 有效括号字符串 。 - 字符串可以写为
(A),其中A是一个 有效括号字符串 。
类似地,可以定义任何有效括号字符串 S 的 嵌套深度 depth(S):
depth("") = 0depth(C) = 0,其中C是单个字符的字符串,且该字符不是"("或者")"depth(A + B) = max(depth(A), depth(B)),其中A和B都是 有效括号字符串depth("(" + A + ")") = 1 + depth(A),其中A是一个 有效括号字符串
例如:""、"()()"、"()(()())" 都是 有效括号字符串(嵌套深度分别为 0、1、2),而 ")(" 、"(()" 都不是 有效括号字符串 。
给你一个 有效括号字符串 s,返回该字符串的 s 嵌套深度 。
示例 1:
输入:s = "(1+(2*3)+((8)/4))+1" 输出:3 解释:数字 8 在嵌套的 3 层括号中。
示例 2:
输入:s = "(1)+((2))+(((3)))" 输出:3
提示:
1 <= s.length <= 100s由数字0-9和字符'+'、'-'、'*'、'/'、'('、')'组成- 题目数据保证括号表达式
s是 有效的括号表达式
# 二、题目解析
# 三、参考代码
# 1、Java 代码
class Solution {
public int maxDepth(String s) {
int ans = 0, size = 0;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (ch == '(') {
++size;
ans = Math.max(ans, size);
} else if (ch == ')') {
--size;
}
}
return ans;
}
}
# **2、C++ **代码
class Solution {
public:
int maxDepth(string s) {
int ans = 0, size = 0;
for (char ch : s) {
if (ch == '(') {
++size;
ans = max(ans, size);
} else if (ch == ')') {
--size;
}
}
return ans;
}
};
# 3、Python 代码
class Solution:
def maxDepth(self, s: str) -> int:
# size 表示栈的大小
# ans 表示 size 的最大值,也就是最终的结果值
ans, size = 0, 0
# 遍历字符串 s
for ch in s:
# 如果遇到了一个左括号,将其入栈
if ch == '(':
# 栈中元素的个数加 1
size += 1
# 更新深度的值
ans = max(ans, size)
# 如果遇到了一个右括号,弹出栈顶的左括号
elif ch == ')':
# 栈中元素的个数减 1
size -= 1
# 返回最大值
return ans