Description
1. Problem Description
An arithmetic expression contains parentheses, square brackets, and curly brackets.
Programming to determine whether the brackets in the expression are correctly matchedAlgorithm
2. Algorithms
Sequential Scan arithmetic expression
If the arithmetic expression scan is complete, if the stack is empty, the system returns the correct result (0). If the stack is not empty, the left parenthesis is more than the right brace, and the system returns the result (-3)
Extract a character from the arithmetic expression. If it is a left brace ('or' ['or' {'), push it into the stack)
If it is a right parenthesis (')' or ']' or '}'):
(1) If the stack is empty, it means that there are more right brackets than left parentheses, and return (-2)
(2) If the stack is not empty, a bracket (POP) pops up from the top of the stack. If the parentheses match, 1 is used for further judgment. Otherwise, the matching order of left and right parentheses is incorrect, return (-1)
Input
Row 1: Number of samples, assumed n.
The second to n + 1 rows, each row is a sample (arithmetic expression string), n test samples in total.
Output
There are n rows in total, and each row is a test result with four results:
0: matching between left and right brackets is correct.
-1: Incorrect matching order of left and right brackets
-2: There are more right brackets than left brackets.
-3: More left brackets than right brackets
Sample Input 4
{[(1 + 2) * 3-1]
{[(1 + 2] * 3)-1}
{[(1 + 2) * 3]-1}
(1 + 2) * 3)-1}
Sample output -3
-1
0
-2