Reverse Substrings Between Each Pair of Parentheses - Problem
You are given a string s consisting of lowercase English letters and parentheses. Your task is to reverse the substrings enclosed within each pair of matching parentheses, starting from the innermost pairs and working outward.
Think of it like peeling an onion - you process the innermost parentheses first, reverse their content, then move to the outer layers. The final result should not contain any parentheses.
Example: If you have "(abcd)", you reverse "abcd" to get "dcba". For nested cases like "(u(love)i)", you first reverse "love" to get "evol", making it "(uevoli)", then reverse the outer content to get "iloveu".
Input & Output
example_1.py โ Basic Case
$
Input:
s = "(abcd)"
โบ
Output:
"dcba"
๐ก Note:
We have one pair of parentheses containing "abcd". Reversing it gives "dcba" and we remove the parentheses.
example_2.py โ Nested Parentheses
$
Input:
s = "(u(love)i)"
โบ
Output:
"iloveu"
๐ก Note:
First reverse innermost "love" โ "evol", giving "(uevoli)". Then reverse "uevoli" โ "iloveu".
example_3.py โ Multiple Pairs
$
Input:
s = "(ed(et(oc))el)"
โบ
Output:
"leetcode"
๐ก Note:
Process innermost first: "oc" โ "co", then "etco" โ "octe", finally "edocteel" โ "leetcode".
Constraints
- 1 โค s.length โค 2000
- s only contains lowercase English letters and parentheses
- It is guaranteed that all parentheses are balanced
Visualization
Tap to expand
Understanding the Visualization
1
Enter outer doll
Start processing the outermost parentheses level
2
Dive deeper
When we find '(', we go to the next nesting level
3
Hit the core
Process the innermost content first
4
Reverse and bubble up
Reverse content and merge with the previous level
5
Complete the message
Continue until all levels are processed
Key Takeaway
๐ฏ Key Insight: Use a stack to naturally handle the nested structure, processing inner levels first and bubbling results upward through reversals.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code