Reverse inside the brackets
Reverse the text inside each pair of brackets, from the innermost outward, by keeping one piece of text per open level on a stack. About 16 minutes.
A piece of text per level
In (u(love)i), the text love is reversed to evolve, then u plus evolve plus i is reversed, giving iloveu. The inner group is dealt with before the outer one, and that is just what a stack gives you.
Keep the current piece of text. When an opener arrives, push the current piece onto the stack and begin a fresh, empty one.
if ch == "(":
stack.append(cur)
cur = []
else:
cur.append(ch)The opener saved the empty text and started a new piece. Then u was added: u.
Reverse and glue at a closer
A closer ends the innermost group, so the current piece is its finished text. Reverse it. Then take the saved piece off the stack and add the reversed text to its end, and make that the current piece again.
Neither kind of bracket is ever added to the output. When the string ends, the current piece is the answer.
elif ch == ")":
cur.reverse()
prev = stack.pop()
prev.extend(cur)
cur = prevWhat does the text (ab(cd)) become after reversing inside each pair?
- Adcba
- Bcdba
- Cabcd
Show the answer
cdba. Inner: cd becomes dc, so the outer text is abdc. Reversing it gives cdba.
Reverse substrings between brackets
You are given a string s of lowercase letters and round brackets, in which the brackets are balanced. Reverse the characters inside each pair of matching brackets, starting with the innermost pair, and return the result without any brackets.
s = "(u(love)i)" → "iloveu"
0 ≤ length of s ≤ 2,000 · s has lowercase letters and balanced round brackets