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;
}
};