Suppose we have a string s with parenthesis '(' , ')' and lowercase English characters. We have to delete the minimum number of parentheses ( '(' or ')', from any positions ) so that the resulting parentheses string is valid and have to finally return any valid string. Here the parentheses string is valid when all of these criteria are fulfilled −
The string is empty and contains lowercase characters only, or
The string can be written as AB (A concatenated with B), where A and B are valid strings, or
The string can be written as the form of (A), where A is a valid string.
So, if the input is like s = "m)n(o)p", then the output will be "mn(o)p"
To solve this, we will follow these steps −
stack := a new list
indexes := a new set
i := 0
for each c in s, do
if c is same as '(', then
push i into stack
otherwise when c is same as ')', then
if size of stack is same as 0, then
insert i into indexes
otherwise,
pop from stack
i := i + 1
ret := blank string
indexes := store all elements into indexes
for i in range 0 to size of s - 1, do
if i not in indexes, then
ret := ret + s[i]
return ret
Example
Let us see the following implementation to get better understanding −
def solve(s):
stack = []
indexes = set()
i = 0
for c in s:
if c == '(':
stack.append(i)
elif c == ')':
if len(stack) == 0:
indexes.add(i)
else:
stack.pop()
i += 1
ret = ''
indexes = indexes.union(stack)
for i in range(len(s)):
if i not in indexes:
ret += s[i]
return ret
s = "m)n(o)p"
print(solve(s))Input
"m)n(o)p"
Output
mn(o)p