Skip to content

Commit f713321

Browse files
feat(reverse-string-brackets): reverse the strings inside the brackets challenge
1 parent 0125d67 commit f713321

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
Given a string with valid brackets (could have multiple nested brackets),
3+
reverse the contents of the brackets and return the string with the reversed
4+
content and no brackets
5+
"""
6+
7+
8+
def reverseChars(chars, left, right):
9+
while left < right:
10+
chars[left], chars[right] = chars[right], chars[left]
11+
left += 1
12+
right -= 1
13+
14+
15+
def reverseStringBrackets(string):
16+
if not string:
17+
return ''
18+
19+
chars = list(string)
20+
stack = []
21+
for idx, char in enumerate(chars):
22+
if char == '(':
23+
stack.append(idx)
24+
elif char == ')':
25+
left = stack.pop()
26+
reverseChars(chars, left + 1, idx - 1)
27+
28+
return ''.join(filter(lambda s: s not in {'(', ')'}, chars))
29+
30+
31+
print(reverseStringBrackets('(Hello)World'))
32+
print(reverseStringBrackets('World(Hello)'))
33+
print(reverseStringBrackets('((HelloWorld))'))
34+
print(reverseStringBrackets('(HelloWorld)'))
35+
print(reverseStringBrackets('(Hello)(World)'))
36+
print(reverseStringBrackets('(Hello(World)Good)'))

0 commit comments

Comments
 (0)