![]() |
VOOZH | about |
Given a string str that consists of lowercase English letters and brackets. The task is to reverse the substrings in each pair of matching parentheses, starting from the innermost one. The result should not contain any brackets.
Examples:
Input: str = "(skeeg(for)skeeg)"
Output: geeksforgeeksInput: str = "((ng)ipm(ca))"
Output: camping
Approach: This problem can be solved using a stack. First, whenever a '(' is encountered then push the index of the element into the stack, and whenever a ')' is encountered then get the top element of the stack as the latest index and reverse the string between the current index and index from the top of the stack. Follow this for the rest of the string and finally print the updated string.
Below is the implementation of the above approach:
geeksforgeeks
Time Complexity: O(n2), where n is the length of the given string.
Auxiliary Space: O(n)
Efficient Approach:
Our Approach is simple and we can reduce the space complexity from O(n) to O(1) that is constant space .
Approach:
We create a function for reversing substrings between the opening and closing brackets one by one, beginning with the innermost one. We can use a while loop to keep doing this until we run out of brackets.
In each iteration of the while loop, we first find the index of the string's initial closing bracket. We exit the loop if there is no closing bracket. Otherwise, we search backwards from the closing bracket to identify the appropriate starting bracket.
The reverseSubstring function is then used to reverse the substring between the opening and closing brackets. Finally, we use the erase function to delete the opening and closing brackets from the string.
Implementation:
geeksforgeeks
Time Complexity: O(n^2), where n is the length of the given string.
Auxiliary Space: O(1),No extra space is used.