Leetcode 1614. Maximum Nesting Depth of the Parentheses
Given a valid parentheses string s
(a string consisting of (
and )
only), we need to compute the maximum depth of valid nested parentheses.
Example:
To find the maximum depth of nested parentheses:
(
, increase the depth counter.)
, decrease the depth counter.#include <string>
#include <algorithm>
class Solution {
public:
int maxDepth(std::string s) {
int current_depth = 0;
int max_depth = 0;
for (char ch : s) {
if (ch == '(') {
current_depth++;
max_depth = std::max(max_depth, current_depth);
} else if (ch == ')') {
current_depth--;
}
}
return max_depth;
}
};
The time complexity of this solution is O(n), where n is the length of the input string s
. This is because we only perform a single traversal of the string.
current_depth
and max_depth
to 0.s
.(
, we increment current_depth
and update max_depth
if the current depth exceeds the previous max_depth
.)
, we decrement current_depth
.max_depth
will hold the maximum depth of the nested parentheses in the string.This approach ensures that we efficiently and accurately determine the maximum nesting depth in a single pass through the input string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?