- The input string s consists of parentheses characters '(' and ')' only.
- The length of s is between 1 and 1000.
Example:
Input: "(A)"
Output: 1
Explanation: The depth of the parentheses is 1.
Input: "((A+B))+(A(B-(C*D)))"
Output: 3
Explanation: The depth of the parentheses is 3.
Maximum Depth of Nested Parenthesis using Stack.
In this approach, we use a stack to track the depth of the parenthesis at any particular moment while traversing the given parenthesis string. We will also keep a variable to keep updating the maximum depth whenever we meet a closing parenthesis.
Algorithm Steps:
- Initialize an empty stack to keep track of opening parenthesis.
- Create a variable count and initialize it with 0, it will store the maximum depth of nested parenthesis.
- Traverse the given input string and follow the below steps:
- If the character is opening parenthesis '(' then push it into the stack.
- If the character is a closing parenthesis ')' then update the value of the count if it is less than the current stack size. Pop an element from the stack.
- Return the count variable as the maximum depth of parenthesis.
Below is the code implementation of the above approach:
// C++ code to find the maximum depth // of nested parenthesis #include <iostream> #include<stack> using namespace std; int maxDepth(string str) { stack<char> st; int count = 0; for(char c:str) { if(c == '(') { // insert the opening parenthesis st.push(c); }else if(c == ')'){ // update the max depth if(count < st.size()) { count = st.size(); } st.pop(); } } return count; } int main() { string str = "((A+B))+(A(B-(C*D)))"; int result = maxDepth(str); cout<< "Maximum Depth: " <<result <<endl; return 0; }
// Java code implementation to find maximum // depth of nested parenthesis import java.util.Stack; public class Main { public static void main(String[] args) { String str = "((A+B))+(A(B-(C*D)))"; int result = maxDepth(str); System.out.println("Maximum Depth: " + result); } public static int maxDepth(String str) { Stack<Character> st = new Stack<>(); int count = 0; for (char c : str.toCharArray()) { // insert the opening parenthesis in stack if (c == '(') { st.push(c); } else if (c == ')') { // update the max depth if (count < st.size()) { count = st.size(); } st.pop(); } } return count; } }
# Python code to find the max depth of parenthesis def max_depth(s): stack = [] max_depth = 0 for char in s: if char == '(': stack.append(char) elif char == ')': if len(stack) > max_depth: max_depth = len(stack) stack.pop() return max_depth s = "((A+B))+(A(B-(C*D)))" result = max_depth(s) print("Maximum Depth:", result)
// C# code to find max depth of nested parenthesis using System; using System.Collections.Generic; class Program { static void Main() { string str = "((A+B))+(A(B-(C*D)))"; int result = MaxDepth(str); Console.WriteLine("Maximum Depth: " + result); } public static int MaxDepth(string str) { Stack<char> st = new Stack<char>(); int count = 0; foreach (char c in str) { if (c == '(') { st.Push(c); } else if (c == ')') { if (count < st.Count) { count = st.Count; } st.Pop(); } } return count; } }
Maximum Depth: 3
- Time Complexity: O(n) where n is the size of the given input string.
- Space Complexity: O(n) as we are using an extra stack to store open parenthesis.
Maximum Depth of Nested Parenthesis Without Using Stack.
In this approach, we are not using any additional data structure like stack. If we observe the previous solution carefully then we figure out that whenever we meet a close parenthesis we are checking the current depth of the stack so we do not need to store the element in the stack. Instead, we can use a variable that will tell us the current depth, and each time we meet a closing parenthesis we will update the maximum of current and previous depth.
Algorithm steps:
- Initialize a variable depth to keep track of the current nesting depth. Initially set to 0.
- Initialize a variable ans to store the maximum depth encountered during the iteration. Initially set to 0.
- Iterate through the given string and follow the steps below:
- If the current character is opening parenthesis then increase the value of depth by 1.
- Update ans with the maximum value between its current value and the current depth.
- If the current character is a closing parenthesis ')', decrement the depth to indicate the end of nesting.
- After iterating through the entire string, return the final maximum depth stored in ans.
Below is the code implementation of the above approach:
// C++ code to find the maximum depth // of nested parenthesis without stack #include <iostream> #include<stack> using namespace std; int maxDepth(string str) { int depth = 0; int ans = 0; for(char c:str) { if(c == '(') { depth++; // update the current max depth ans = max(ans, depth); }else if(c == ')'){ depth--; } } return ans; } int main() { string str = "((A+B))+(A(B-(C*D)))"; int result = maxDepth(str); cout<< "Maximum Depth: " <<result <<endl; return 0; }
// Java code to find the maximum depth // of nested parenthesis without stack public class MaxDepth { public static int maxDepth(String str) { int depth = 0; int ans = 0; for (char c : str.toCharArray()) { if (c == '(') { depth++; ans = Math.max(ans, depth); } else if (c == ')') { depth--; } } return ans; } public static void main(String[] args) { String str = "((A+B))+(A(B-(C*D)))"; int result = maxDepth(str); System.out.println("Maximum Depth: " + result); } }
# Maximum Depth of parenthesis in O(1) space def max_depth(s): depth = 0 ans = 0 for c in s: if c == '(': depth += 1 ans = max(ans, depth) elif c == ')': depth -= 1 return ans str_input = "((A+B))+(A(B-(C*D)))" result = max_depth(str_input) print("Maximum Depth:", result)
// C# code to find depth of nested parenthesis using System; class Program { static int MaxDepth(string str) { int depth = 0; int ans = 0; foreach (char c in str) { if (c == '(') { depth++; ans = Math.Max(ans, depth); } else if (c == ')') { depth--; } } return ans; } static void Main() { string str = "((A+B))+(A(B-(C*D)))"; int result = MaxDepth(str); Console.WriteLine("Maximum Depth: " + result); } }
Output:
Maximum Depth: 3
- Time Complexity: O(n) where n is the size of the input string.
- Space Complexity: O(1) as we are not using any extra space except two variables to store the current and maximum depth.
No comments:
Post a Comment