Skip to content

Instantly share code, notes, and snippets.

@Greenheart
Created February 27, 2018 12:07
Show Gist options
  • Save Greenheart/dbfc892a36e9241f0c07eea859bb6112 to your computer and use it in GitHub Desktop.
Save Greenheart/dbfc892a36e9241f0c07eea859bb6112 to your computer and use it in GitHub Desktop.
My solution to a challenge from https://codefights.com
/*
Samuel Plumppu - 2018-02-27
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.
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".
*/
function reverseParentheses (s) {
let result = s
while (result.includes('(')) {
result = reverseParenthesis(result)
}
return result
}
// This regex matches a complete parenthesis that has no other parentheses inside of it.
const innermostParenthesis = /\([^(]*?\)/
// The negated set "[^(]" makes sure that we only capture the innermost parenthesis.
// Likewise, the lazy quantifier "?" makes sure that it stops when the innermost parenthesis ends.
function reverseParenthesis (s) {
// Replace the deepest parenthesis with its reversed content.
// 1. Split into chars.
// 2. Slice to remove first and last chars (the parenthesis).
// 3. Reverse and join to a string.
return s.replace(innermostParenthesis, content => (
[...content].slice(1, -1)
.reverse().join('')
))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment