Answer the question
In order to leave comments, you need to log in
Determine the beginning and end of parentheses from a String and put them in the correct order?
Given a string of the form
String fileStr= "['2', '3', ['b','a', ['A', 'B'], 'S', ['R'] ], 'G', ['Z']]";
StringBuilder str= new StringBuilder(fileStr);
ArrayList<Integer> tokenIndexStart = new ArrayList<>();
ArrayList<Integer> tokenIndexEnd = new ArrayList<>();
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) == '[') {
tokenIndexStart.add(i);
} else if (str.charAt(i) == ']') {
tokenIndexEnd.add(i);
}
}
Answer the question
In order to leave comments, you need to log in
As I understand it, your brackets are placed correctly in the line, and you need to match between the brackets.
Use a stack. Loop through the line. When an opening brace is encountered, push its position onto the stack. When a closing brace is encountered, pop the position of the corresponding opening brace from the stack. Parentheses are placed incorrectly if something is left on the stack after processing the entire string, or if you encounter a closing parenthesis when the stack is empty.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question