Skip to content

Latest commit

 

History

History
23 lines (20 loc) · 810 Bytes

1614.maximum-nesting-depth-of-the-parentheses.md

File metadata and controls

23 lines (20 loc) · 810 Bytes

Stack

We can use stack to trace the depth of the parentheses. When we meet a (, we push it into the stack. When we meet a ), we pop the stack and update the maximum depth. To optimizee the space complexity, we can use a variable to store the count of unmatched left parentheses and update the maximum depth.

fun maxDepth(s: String): Int {
    var maxDepth = 0
    var leftCount = 0
    for (c in s) {
        if (c == '(') {
            leftCount++
            maxDepth = maxOf(maxDepth, depth)
        } else if (c == ')') {
            leftCount--
        }
    }
    return maxDepth
}
  • Time Complexity: O(n).
  • Space Complexity: O(1).