Start learning free

LESSON 475 OF 674 · STACK

Reverse Substrings Between Each Pair Of Parentheses

Practice O(n^2)

You get a string s of lowercase letters and parentheses. Every ( has its own ).

Return the string that is left when all the parentheses are gone.

Remove them from the inside out. Take an innermost pair and reverse the letters between its brackets. Then delete the two brackets. Repeat until no brackets are left.


Example 1:

Input: s = "my(tac)"
Output: "mycat"

Example 2:

Input: s = "(ek(ca)nap)"
Output: "pancake"
Explanation: The inner pair turns "ca" into "ac".
That leaves "(ekacnap)".
Reversing it gives "pancake".

Example 3:

Input: s = "(ab)()(cd)"
Output: "badc"
Explanation: "ab" becomes "ba".
"cd" becomes "dc".
The empty pair adds nothing.

Constraints:

  • s has 1 to 2,000 characters.
  • Each character is a lowercase English letter, ( or ).
  • Every bracket is matched.

STEP 1 OF 9
    Ctrl + Enter to check