File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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)' ))
You can’t perform that action at this time.
0 commit comments