To determine if all delimiters are matched and closed, we need to use a stack data structure:
Push open delimiters: Whenever we encounter an open delimiter ({, [, (), push it onto the stack.
Check close delimiters: For a close delimiter (}, ], )), check if the stack is empty or if the top of the stack does not have the corresponding open delimiter. If so, the delimiters aren’t matched.
Final check: After processing the entire expression, the stack should be empty. If it’s not, some open delimiters don’t have corresponding close delimiters.
Here is the approach:
Initialize a stack: Create an empty stack to store open delimiters.
Process the expression: Traverse characters in the expression.
Push open delimiters onto the stack.
For each close delimiter, check the stack for a matching open delimiter.
Return the result: If the stack is empty after processing, all delimiters are matched.