Skip to content

Commit b89ca30

Browse files
committed
added Reverse Substrings Between Each Pair of Parentheses (medium)
1 parent 9d1c8d7 commit b89ca30

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
# Reverse Substrings Between Each Pair of Parentheses
3+
[Leetcode Link](https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/)
4+
5+
## Problem:
6+
7+
You are given a string `s` that consists of lower case English letters and brackets.
8+
9+
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
10+
11+
Your result should **not** contain any brackets.
12+
13+
## Example:
14+
15+
```
16+
Input: s = "(abcd)"
17+
Output: "dcba"
18+
```
19+
```
20+
Input: s = "(u(love)i)"
21+
Output: "iloveu"
22+
Explanation: The substring "love" is reversed first, then the whole string is reversed.
23+
```
24+
```
25+
Input: s = "(ed(et(oc))el)"
26+
Output: "leetcode"
27+
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.
28+
```
29+
```
30+
Input: s = "a(bcdefghijkl(mno)p)q"
31+
Output: "apmnolkjihgfedcbq"
32+
```
33+
34+
## Note:
35+
36+
- `0 <= s.length <= 2000`
37+
- `s` only contains lower case English characters and parentheses.
38+
- It's guaranteed that all parentheses are balanced.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def reverseParentheses(self, s: str) -> str:
3+
stack = list()
4+
queue = list()
5+
for c in s:
6+
# reverse string on ')'
7+
if c == ')':
8+
top = stack.pop()
9+
while top != '(':
10+
queue.append(top)
11+
top = stack.pop()
12+
# insert reversed substr back into stack
13+
while queue:
14+
stack.append(queue.pop(0))
15+
else:
16+
stack.append(c)
17+
return "".join(stack)
18+
19+
20+
# test driver
21+
sol = Solution()
22+
# s = "(ed(et(oc))el)"
23+
s = "a(bcdefghijkl(mno)p)q"
24+
print("Input:", s)
25+
print("Output:", sol.reverseParentheses(s))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Languages used: Java and Python
5959
- [Swap Nodes in Pairs](Medium/SwapNodesInPairs)
6060
- [All Paths From Source to Target](Medium/AllPathsFromSrcToTarget)
6161
- [Queens That Can Attack The King](Medium/QueensThatCanAttackKing)
62+
- [Reverse Substrings Between Each Pair of Parentheses](Medium/ReverseSubstringsBetweenParentheses)
6263
- Hard
6364

6465
---

0 commit comments

Comments
 (0)