Skip to main content

1614. 括号的最大嵌套深度

思路

从题目上看,其实就是统计有多少个连续左括号,遇到左括号就加1,遇到右括号说明退出了一层括号,所以减1,每次更新一下最大值。

tip

记录最大值可以在循环内部每次求一次max

代码

class Solution {
public:
int maxDepth(string s) {
int ans = 0, cnt = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') cnt ++;
else if (s[i] == ')') cnt --;
ans = max(ans, cnt);
}
return ans;
}
};