The essential feature is that when a closing delimiter is encountered, it should be a match for the most recent opening delimter.
Using this fact ("most recent"), a stack holding the opening delimiters can be used:
-
When a character is read, just print it.
-
If the character is an opening delimiter, push it on the stack.
-
If the character is a closing delimiter, check that is a match for the top element of the stack (the most recent opening delimiter).
If there is a match, just pop the opening delimiter off the stack, otherwise the input is not balanced.
Some details:
What if the stack is not empty after all the input has been read?
What if a closing delimiter is read, but the stack is empty?
(See hw2.)