https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
- Stack
- String
Track the current depth while scanning parentheses and update the maximum depth.
O(n)
O(1)
class Solution {
public int maxDepth(String s) {
int depth = 0, ans = 0;
for (char c : s.toCharArray()) {
if (c == '(') ans = Math.max(ans, ++depth);
else if (c == ')') depth--;
}
return ans;
}
}