1614. Maximum Nesting Depth of the Parentheses
1 min read
LeetCode Daily Problem: Maximum Nesting Depth of the Parentheses
Given a valid parentheses string s, return the nesting depth of **s. The nesting depth is the maximum number of nested parentheses.
Constraints:
1 <= s.length <= 100sconsists of digits0-9and characters'+','-','*','/','(', and')'.- It is guaranteed that parentheses expression
sis a VPS.
Approach
This is almost too easy; here is the code.
On second thought, let me explain the idea. It is like finding the maximum value in an array without max(): scan once and keep the largest value. Here, scan the parentheses and keep the maximum depth.
python
class Solution:
def maxDepth(self, s: str) -> int:
cur = 0
max_num = 0
for c in s:
if c == '(':
cur += 1
max_num = max(max_num, cur)
elif c == ')':
cur -= 1
return max_numTime complexity is O(n); space complexity is O(1).
SeriesDaily Problem →
TagsStackSimulation