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).