Search code examples
javascriptreverseparentheses

ReverseParentheses - Codefights


I'm having a really tough time solving this problem with JavaScript

You are given a string s that consists of English letters, punctuation marks, whitespace characters and brackets. It is guaranteed that the brackets in s form a regular bracket sequence.

Your task is to reverse the strings in each pair of matching parenthesis, starting from the innermost one.

Example

For string s = a(bc)de the output should be

reverseParentheses(s) = "acbde".

Input/Output

[time limit] 4000ms (js)
[input] string s

A string consisting of English letters, punctuation marks, whitespace characters and brackets. It is guaranteed that parenthesis form a regular bracket sequence.

Constraints:

5 ≤ x.length ≤ 55.

[output] string

It has to work with the following inputs:

  1. s: a(bcdefghijkl(mno)p)q Expected Output: apmnolkjihgfedcbq
  2. s: co(de(fight)s) Expected Output: cosfighted

Solution

  • function reverseParentheses(s) {
        if (s.includes('(')){
            return reverseParentheses(reverseOnce(s));
        } else {     
            return s;
        }
    }
    
    function reverseOnce(s){
        var regexp = /\(([^()]*)\)/i;
        var subStr = regexp.exec(s)[1];
        subStr = subStr.split('').reverse().join('');
        return s.replace(regexp, subStr)
    }