Reverse in Parenthesis
https://app.codesignal.com/arcade/intro/level-3/9DgaPsE2a7M6M2Hu6
---
Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()
s.
Example
- For
inputString = "(bar)"
, the output should bereverseInParentheses(inputString) = "rab"
; - For
inputString = "foo(bar)baz"
, the output should bereverseInParentheses(inputString) = "foorabbaz"
; - For
inputString = "foo(bar)baz(blim)"
, the output should bereverseInParentheses(inputString) = "foorabbazmilb"
; - For
inputString = "foo(bar(baz))blim"
, the output should bereverseInParentheses(inputString) = "foobazrabblim"
.
Because"foo(bar(baz))blim"
becomes"foo(barzab)blim"
and then"foobazrabblim"
.
Input/Output
[execution time limit] 3 seconds (java)
[input] string inputString
A string consisting of lowercase English letters and the characters
(
and)
. It is guaranteed that all parentheses ininputString
form a regular bracket sequence.Guaranteed constraints:
0 ≤ inputString.length ≤ 50
.[output] string
- Return
inputString
, with all the characters that were in parentheses reversed.
- Return
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int i; | |
String reverseInParentheses(String inputString) { | |
i = 0; | |
return dfs(inputString); | |
} | |
String dfs(String s) { | |
if (i == s.length()) { | |
return ""; | |
} | |
StringBuilder sb = new StringBuilder(); | |
while (i < s.length()) { | |
if (s.charAt(i) == '(') { | |
i++; | |
sb.append(dfs(s)); | |
} else if (s.charAt(i) == ')') { | |
i++; | |
return sb.reverse().toString(); | |
} else { | |
sb.append(s.charAt(i++)); | |
} | |
} | |
return sb.toString(); | |
} |