# [Java] Reverse content in brackets

Question:

Input String may have content inside of brackets. All the content in brackets should be in reversed order.

Ex:

• Input — “Hello(Welcome)” Outcome — “HelloomocleW”
• Input — “Hello(Wel(co)me)” Outcome — “HelloomcoleW”

Assumptions:

• Brackets will be in the standard way (Which means those not gonna messes up the content. All open brackets will have close brackets)

There will be several answers which we can come up with good answers. I came up with an answer with a Recursive method call.

import java.util.Stack;

public class Solution {
static String strFinal = "";
static Integer reversedInteger ;
public static void main(String[] args) {
String result = reversedString("Hello(We(lc)ome)");
System.out.println(result);
}
static String reversedString (String input){
StringBuilder s = new StringBuilder(input);
for (int i=0; i<s.length(); i++) {
if(s.charAt(i) == '(') {
strFinal = strFinal + stackReverse(input,i+1);
i = reversedInteger;
}else if (s.charAt(i) == ')');
else {
strFinal = strFinal+ s.charAt(i);
}
}
return strFinal;
}

static String stackReverse (String S, Integer index){
Stack<Character> temporarystack = new Stack();
String reversedStringByStack = "";
for (int i=index; i<S.length(); i++) {
if (S.charAt(i) == '(') {
StringBuilder reversed = new StringBuilder(stackReverse(S, i+1));
for(int k =0; k<reversed.length();k++){
temporarystack.push(reversed.charAt(k));
}
i = reversedInteger;
}
else if (S.charAt(i) == ')') {
reversedInteger = i;
break;
} else {
temporarystack.push(S.charAt(i));
}
}
while (!temporarystack.isEmpty()){
reversedStringByStack = reversedStringByStack + temporarystack.pop();
}
return reversedStringByStack;
}
}