Suppose, we have a lowercase string s that contains letters and parentheses "(" and ")". We have to reverse every string enclosed within parentheses in a recursive manner and return the resultant string.
So, if the input is like s = "back(aps)ce", then the output will be “backspace”.
To solve this, we will follow these steps −
Define a function trav() . This will take s, dir, start, close:= close, ans:= ans
end := "(" if dir is same as −1, otherwise ")"
other := "(" if end is same as ")", otherwise ")"
while start < size of s, and s[start] is not same as end, do
if s[start] is same as other, then
trav(s, -dir, close[other, start] - dir)
start := close[other, start] + dir
otherwise,
insert s[start] at the end of ans
start := start + dir
From the main function, do the following −
ans := a new list
close := a new map containing keys “)” and “(” initially the values are two empty maps
stack := a new list
for each index I and value c in s, do
if c is same as "(", then
push i into stack
otherwise when c is same as ")", then
o := top of stack, then pop from stack
close[")", i] := o
close["(", o] := i
trav(s, 1, 0)
return ans joined with blank string
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): ans = [] close = {")": {}, "(": {}} stack = [] for i, c in enumerate(s): if c == "(": stack.append(i) elif c == ")": o = stack.pop() close[")"][i] = o close["("][o] = i def trav(s, dir, start, close=close, ans=ans): end = "(" if dir == -1 else ")" other = "(" if end == ")" else ")" while start < len(s) and s[start] != end: if s[start] == other: trav(s, −dir, close[other][start] − dir) start = close[other][start] + dir else: ans.append(s[start]) start += dir trav(s, 1, 0) return "".join(ans) ob = Solution() print(ob.solve("back(aps)ce"))
Input
"back(aps)ce"
Output
backspace