-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add solution to the 'Reverse in parenthesis' challenge
Add java and js solutions
- Loading branch information
Showing
4 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.