返回一个字符串的中括号嵌套的深度:
法一:直接用栈处理括号,深度破纪录时记录一下即可:
class Solution {
public:
int maxDepth(string s) {
stack<char> cs;
int maxDep = 0;
for (char c : s) {
if (c == '(') {
cs.push(c);
if (cs.size() > maxDep) {
maxDep = cs.size();
}
} else if (c == ')' && cs.top() == '(') {
cs.pop();
}
}
return maxDep;
}
};
法二:简化法一不用栈,直接计数:
class Solution {
public:
int maxDepth(string s) {
int curDepth = 0, max = 0;
for (char c : s) {
if (c == '(') {
++curDepth;
if (max < curDepth) {
max = curDepth;
}
}
if (c == ')' && curDepth > 0) {
--curDepth;
}
}
return max;
}
};