Stack Matching Experiment

Source: Internet
Author: User
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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.