I need to extract lines from nested brackets as follows:
[ this is [ hello [ who ] [what ] from the other side ] slim shady ]
Result (Order does not matter) :
This is slim shady Hello from the other side Who What
Note that a string can have N brackets, and they will always be valid, but may or may not be nested. In addition, the line should not begin with a bracket.
The solutions I found on the Internet on a similar problem offer a regex, but I'm not sure if it will work in this case.
I was thinking of implementing this, similar to how we check if a string has all valid parentheses:
Go through the line. If we see [we push its index onto the stack, if we see], we adjust from there to the current place.
However, we need to remove this substring from the original string so that we do not get it as part of any of the outputs. So, instead of just pushing the index onto the stack, I was thinking of creating a LinkedList as we move forward, and when we find [we put this Node into the LinkedList. This will allow us to easily remove the substring from LinkedList.
Would this be a good approach or is there a cleaner, more well-known solution?
EDIT:
'[ this is [ hello [ who ] [what ] from the other [side] ] slim shady ][oh my [g[a[w[d]]]]]'
Must be returned (Order does not matter) :
this is slim shady hello from the other who what side oh my g a w d
White spaces do not matter which are trivial for subsequent removal. It is important to be able to distinguish between different contents in parentheses. Either separating them in new lines, or having a list of lines.