Reverse Parentheses
Description
You have a string s
that consists of English letters, punctuation marks, whitespace characters, and brackets. It is guaranteed that the parentheses in s
form a regular bracket sequence.
Note: A bracket sequence is called regular if it is possible to insert some numbers and signs into the sequence in such a way that the new sequence will represent a correct arithmetic expression.
Your task is to reverse the strings contained in each pair of matching parentheses, starting from the innermost pair. The results string should not contain any parentheses.
Example
For string s = "a(bc)de"
, the output should be
reverseParentheses(s) = "acbde"
.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] string s
A string consisting of English letters, punctuation marks, whitespace characters and brackets. It is guaranteed that parentheses form a regular bracket sequence.
Constraints:
5 ≤ s.length ≤ 55
.
- [output] string
Sorted array a
with all the trees untouched.
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
8
function reverseParentheses(s) {
var exp = /\([^()]+\)/;
while (exp.test(s)) {
s = s.replace(exp, (r) => r.split('').slice(1,-1).reverse().join(''));
}
return s;
}