Problem
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
- It is an empty string
"", or a single character not equal to"("or")", - It can be written as
AB(Aconcatenated withB), whereAandBare VPS’s, or - It can be written as
(A), whereAis a VPS.
We can similarly define the nesting depth depth(S) of any VPS S as follows:
depth("") = 0depth(C) = 0, whereCis a string with a single character not equal to"("or")".depth(A + B) = max(depth(A), depth(B)), whereAandBare VPS’s.depth("(" + A + ")") = 1 + depth(A), whereAis a VPS.
For example, "", "()()", and "()(()())" are VPS’s (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS’s.
Given a VPS represented as string s, return the nesting depth of s.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Using counters
To determine the nesting depth of a valid parentheses string:
- Initialize a counter
current_depthto track the current depth as we traverse the string. - Initialize a variable
max_depthto keep track of the maximum depth encountered. - Iterate through each character in the string:
- Increment
current_depthwhen encountering an opening parenthesis(. - Update
max_depthifcurrent_depthexceeds it. - Decrement
current_depthwhen encountering a closing parenthesis).
- Increment
- Return the
max_depthas the nesting depth of the string.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of the string, since we traverse the string once. - 🧺 Space complexity:
O(1), because we use a fixed amount of additional space regardless of the input size.