[Java] Reverse content in brackets

Dilshani Subasinghe
Oct 2, 2018 · 1 min read

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)

Answer:

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store