![]() |
VOOZH | about |
Given a valid parenthesis string str consisting of lowercase alphabets, opening, and closing brackets, the task is to find the string by removing the outermost enclosing brackets such that the string remains a valid parenthesis string.
Examples:
Input: S = "(((a)(bcd)(e)))"
Output: (a)(bcd)(e)
Explanation:
The outermost enclosing brackets are: { S[0], S[1], S[13], S[14] }.
Removing the outermost enclosing brackets from str modifies str to "(a)(bcd)(e)".
Therefore, the required output is (a)(bcd)(e).Input: str = "((ab)(bc))d"
Output: ((ab)(bc))d
Explanation:
Since no outermost enclosing brackets present in the string. Therefore, the required output is ((ab)(bc))d
Approach:The idea is to iterate over the characters of the string and count the number of consecutive opening parenthesis and closing parenthesis from both ends of the string respectively. Then, iterate over the characters present in the inner string and count the number of opening brackets needed to balance out the string. Follow the steps below to solve the problem:
Follow the below steps to solve the problem:
Below is the implementation of the above approach:
((a)b)(c)
Time Complexity: O(N)
Auxiliary Space: O(1)