Problem 230242 · medium · Phase 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 = "(u(love)i)"
Output: "iloveu"
Explanation: inner "love" -> "evol", giving "(uevoli)" -> "iloveu".

Input:  s = "(sn(ed(ra))g)"
Output: "gedarns"

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…