Created
June 13, 2018 19:28
-
-
Save caandradeduarte/e7ceaf827f848564097d7f9f8c50383e 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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