Skip to content

Instantly share code, notes, and snippets.

@kkuivi
Created April 20, 2017 05:58
Show Gist options
  • Save kkuivi/a0794f252c303146f89e8375014c8585 to your computer and use it in GitHub Desktop.
Save kkuivi/a0794f252c303146f89e8375014c8585 to your computer and use it in GitHub Desktop.
CodeFights: reverseParentheses
String reverseParentheses(String s) {
Stack<ParenPair> openingParen = new Stack<>();
Queue<ParenPair> fullParenPair = new LinkedList<>();
StringBuilder sentence = new StringBuilder(s);
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '('){
ParenPair parenPair = new ParenPair(i);
openingParen.push(parenPair);
}
if(c == ')') {
ParenPair fullPair = openingParen.pop();
fullPair.closeIndex = i;
fullParenPair.add(fullPair);
}
}
while(!fullParenPair.isEmpty()) {
ParenPair parenPair = fullParenPair.remove();
int openParen = parenPair.openIndex;
int closeParen = parenPair.closeIndex;
StringBuilder subsequence = new StringBuilder(sentence.substring(openParen+1, closeParen));
subsequence.reverse();
sentence.replace(openParen+1, closeParen, subsequence.toString());
}
for(int i = 0; i < sentence.length(); i++){
char c = sentence.charAt(i);
if(c == '(' || c == ')') {
System.out.println("Char: " + c);
sentence.deleteCharAt(i);
i -= 1;
}
}
return sentence.toString();
}
public class ParenPair {
public int openIndex;
public int closeIndex;
public ParenPair(int openIndex) {
this.openIndex = openIndex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment