@
@
@atambalasi2020-03-08 14:30:37
Java
@atambalasi, 2020-03-08 14:30:37

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']]";

It is necessary to define and close the brackets correctly.
For definition use StringBuilder and ArrayList
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);
            }
        }

Now there are two lists, the first one contains the indices where the beginning of the parenthesis lies, and the second list contains the indices of the closing parenthesis. You need to arrange them so that they close properly. I need to get
1)['2', '3', ['b','a', ['A', 'B'], 'S', ['R'] ], 'G', [' Z']]
2)['b','a', ['A', 'B'], 'S', ['R'] ]
3)['A', 'B']
4) [' R']
5) ['Z']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2020-03-09
@wataru

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 question

Ask a Question

731 491 924 answers to any question