Skip to content

Commit

Permalink
Add solution to the 'Reverse in parenthesis' challenge
Browse files Browse the repository at this point in the history
Add java and js solutions
  • Loading branch information
Brnd08 committed Oct 26, 2023
1 parent 8d16e8c commit 21bf758
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Reverse_In_Parenthesis/Reverse_in_parenthesis.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import java.util.Arrays;
import java.util.function.UnaryOperator;
public class Reverse_in_parenthesis{
public static void main (String[] args){
String[] tests = {
"(bar)",
"foo(bar(baz))blim",
"(abc)d(efg)"
};
for(String test : tests){
System.out.format(" Input: '%s'%n Solution: '%s' %n%n", test, solution(test));
}
}

static String solution(String input){
UnaryOperator<String> mostNestedOperator1 = x -> {
int start = x.lastIndexOf('(');
return (start != -1) ?x.substring(start, x.indexOf(')', start) + 1) :null; // returns most nested with parenthesis
};
for(String mostNested; (mostNested = mostNestedOperator1.apply(input)) != null; )
input = input.replace(mostNested, new StringBuilder(mostNested.substring(1, mostNested.length() - 1)).reverse().toString());
return input;
}
}
21 changes: 21 additions & 0 deletions Reverse_In_Parenthesis/Reverse_in_parenthesis.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function solution(input) {
for(let mostNested; (mostNested=findMostNested(input))!=null;){
input = input.replace(mostNested, mostNested.substring(1, mostNested.length -1).split('').reverse().join(''))
}
return input;
}

function findMostNested(string){
const start = string.lastIndexOf("(");
return start !== -1 ? string.substring(start, string.indexOf(")", start) + 1) :null;
}

const tests = [
"(bar)",
"foo(bar(baz))blim",
"(abc)d(efg)"
];

for (const test of tests) {
console.log(` Input: ${test} \n Inverted: ${solution(test)}\n\n`)
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 21bf758

Please sign in to comment.