Setup
For this challenge, you will be given a string of text and valid parentheses as input. Write a function that will return the string with the text inside parentheses reversed. If there are nested parentheses, then that too must be reversed. This pattern should repeat for however many layers of parentheses there are.
Examples
reverseInParens("h(el)lo") == "h(le)lo");
reverseInParens("a ((d e) c b)") == "a (b c (d e))");
Tests
reverseInParens("one (ruof ((rht)ee) owt)")
reverseInParens("one (two (three) four)")
Good luck and have fun!
This challenge comes from dmercertaylor on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (9)
Haskell
I am by no means an expert in Haskell, just an enthusiast. Feel free to help me improve this code!
Try it.
Rust:
Here's my solution in Python 3, should work in linear time with respect to the length of the input string (edit: should work in O(n) space with respect to input length as well):
edit #2: corrected some spelling/grammar in the code, still functionally the same
edit #3: whoops - I read the original kata and realized I misunderstood how nested strings should be merged; I've corrected the code and ensured the output lines up with the expected output from the original kata
Here is my solution in Javascript. I used codepen so I can test the test values easily. I'll link both that, and the code in js (without the console logs i used for debugging ;) ).
Codepen
Javascript
Much slower and not as elegant solution - using recursion and while loops to concatenate strings. Time complexity is terrible and looking to refactor. Would love any feedback or suggested refactoring!
`function reverseInParens(text) {
// Input - string of text that contains parantheses
// Output - reversed text inside of parantheses
// Constraints - n/a
// Edge Cases - n/a
// create global reverse string
};
`
Java
Not so good solution
Javascript
My solution has both time and space complexity of O(n) I believe. The first pass is to create a tree, the second pass is to convert the tree to a string recursively. In fact, reconstructing a string uses multiple passes but their number is constant (reverse, map, join), and it's possible to rewrite the
toStr
function to use a single pass but the code won't be as concise. Reversion is only done at odd levels as at an even level it is reverted again back to original state.Javascript
Some comments may only be visible to logged-in visitors. Sign in to view all comments.