Skip to content

Latest commit

 

History

History
45 lines (29 loc) · 598 Bytes

File metadata and controls

45 lines (29 loc) · 598 Bytes

Maximum Nesting Depth

Problem Link

https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/


Pattern

  • Stack
  • String

Approach

Track the current depth while scanning parentheses and update the maximum depth.


Time Complexity

O(n)

Space Complexity

O(1)


Java Solution

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