Skip to content

Instantly share code, notes, and snippets.

@maurobaraldi
Forked from caandradeduarte/BracketsUtils.java
Created May 28, 2019 20:33
Show Gist options
  • Save maurobaraldi/efcb5c10e4f2b4969f4336794bd6f060 to your computer and use it in GitHub Desktop.
Save maurobaraldi/efcb5c10e4f2b4969f4336794bd6f060 to your computer and use it in GitHub Desktop.
BairesDev test - Given a string with brackets. If the start index of the open bracket is given, find the index of the closing bracket
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Stack;
public class BracketsUtils {
private static final char OPENING_BRACKET = '[';
private static final char CLOSING_BRACKET = ']';
public static int findClosingBracket(String text, int openingBracketIndex) {
char[] charArray = text.toCharArray();
Map<Integer, Integer> mapBrackets = new LinkedHashMap<>();
Stack<Integer> stackOpeningBrackets = new Stack<>();
for (int i=0; i < charArray.length; i++) {
if (charArray[i] == OPENING_BRACKET)
stackOpeningBrackets.push(i);
if (charArray[i] == CLOSING_BRACKET)
mapBrackets.put(stackOpeningBrackets.pop(), i);
}
return mapBrackets.get(openingBracketIndex);
}
public static void main(String[] args) {
System.out.println("Closing Bracket index: " + findClosingBracket("[ABC[23]][89]", 9));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment