Skip to content

Latest commit

 

History

History
48 lines (44 loc) · 2.37 KB

Reverse_In_Parenthesis.md

File metadata and controls

48 lines (44 loc) · 2.37 KB

🔷 Reverse In Parenthesis 🔷

Challenge description

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

Input/Output

  • [execution time limit] 3 seconds (java)

  • [memory limit] 1 GB

  • [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.

[Java] Syntax Tips

## Solutions:
  • JS solution

    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;
    }
    JS Execution

  • Java solution

    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;
    }
    Java Execution