Skip to content

Instantly share code, notes, and snippets.

@HaiBV
Created October 24, 2019 17:14
Show Gist options
  • Save HaiBV/ce90cad2f067461b2f38b43d57a846fd to your computer and use it in GitHub Desktop.
Save HaiBV/ce90cad2f067461b2f38b43d57a846fd to your computer and use it in GitHub Desktop.
reverseInParentheses.js
function reverseInParentheses(s) {
while (true) {
let c = s.indexOf(")");
if (c === -1) {
break;
}
let o = s.substring(0, c).lastIndexOf("(");
let start = s.substring(0, o);
let middle = s.substring(o + 1, c).split("").reverse().join("");
let end = s.substring(c + 1, s.length);
s = start + middle + end;
}
return s;
}
// ================================= //
function reverseInParentheses(s) {
if (s.includes('(')){
return reverseInParentheses(reverseOnce(s));
} else {
return s;
}
}
function reverseOnce(s){
var regexp = /\(([^()]*)\)/i;
var subStr = regexp.exec(s)[1];
console.log(subStr);
subStr = subStr.split('').reverse().join('');
return s.replace(regexp, subStr)
}
// ================================= //
function reverseInParentheses(inputString) {
while (inputString.includes('(')) {
inputString = inputString.replace(/\(([^()]*)\)/, (_, str) => [...str].reverse().join(''));
}
return inputString;
}
@HaiBV
Copy link
Author

HaiBV commented Oct 24, 2019

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 be
reverseInParentheses(inputString) = "rab";
For inputString = "foo(bar)baz", the output should be
reverseInParentheses(inputString) = "foorabbaz";
For inputString = "foo(bar)baz(blim)", the output should be
reverseInParentheses(inputString) = "foorabbazmilb";
For inputString = "foo(bar(baz))blim", the output should be
reverseInParentheses(inputString) = "foobazrabblim".
Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".

Input/Output

[execution time limit] 4 seconds (js)

[input] string inputString

A string consisting of lowercase English letters and the characters ( and ). It is guaranteed that all parentheses in inputString form a regular bracket sequence.

Guaranteed constraints:
0 ≤ inputString.length ≤ 50.

[output] string

Return inputString, with all the characters that were in parentheses reversed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment