Problem 230242 · medium · Level 02 Linear Data Structures

Reverse Inside Brackets

stacks · strings

A string s contains lowercase letters and balanced parentheses. Reverse the text inside every pair of parentheses, starting from the innermost pair, and return the result with all parentheses removed.

Examples

Input:  s = "(ab(cd)e)"
Output: "ecdba"
Explanation: inner "cd" -> "dc", giving "(abdce)" -> "ecdba".

Input:  s = "(pq(rs)t(uv))"
Output: "uvtrsqp"

Input:  s = "a(bc)de"
Output: "acbde"

Constraints

  • 0 <= len(s) <= 2000
  • Target: O(n**2) is acceptable; O(n) is possible

Goals

  • Treat each `(` as the start of a new segment saved on a stack
  • Reverse the innermost segment and splice it into its parent
Starting Python…